【发布时间】:2017-11-05 09:48:26
【问题描述】:
我想使用 PHP et MongoDB Driver 将日期存储在 MongoDB 集合中。
这是我的部分脚本:
第一次连接:
public function process(){
try{
$this->connexion = new \MongoDB\Driver\Manager($this->dsn);
}
catch(\MongoDB\Driver\Exception\InvalidArgumentException $e){
die("Unable to connect to the MongoDB database : " . $e->getMessage());
} catch(\MongoDB\Driver\Exception\RuntimeException $e){
die("General failure : " . $e->getMessage());
}
}
第二个:文档创建
public function process(){
$dbConnector = dbConnector::instance(); // Instance de connexion à la base de données
$query = new \MongoDB\Driver\BulkWrite;
$query->insert($this->queryArray);
$writeConcern = new \MongoDB\Driver\WriteConcern(\MongoDB\Driver\WriteConcern::MAJORITY, 1000);
//$collection = new \MongoCollection($dbConnector->connexion()->db(), $this->store->collectionName());
try{
$this->result = $dbConnector->connexion()->executeBulkWrite($dbConnector->dbName() . "." . $this->store->collectionName(), $query, $writeConcern);
} catch (\MongoDB\Driver\AuthenticationException $e){
echo "Authentication error : " . $e->getMessage() . "<br />\n";
} catch(\MongoDB\Driver\ConnextionException $e){
echo "Connexion error : " . $e->getMessage() . "<br />\n";
}
catch(\MongoDB\Driver\Exception\RuntimeException $e){
echo "Runtime error : " . $e->getMessage() . "<br />\n";
}
}
$queryArray 属性包含我要创建的键/值对。
添加了一个转换方法,可以管理日期并将其转换为 MongoDB ISODate : 使用 \MongoDB\BSON\UTCDateTime 作为 MongoUTCDate; ... ... 公共静态函数 toISODate($date){ if(is_object($date)){ $dateToString = $date->year 。 “-”。 $日期->月份。 “-”。 $日期->天; } 别的 { $dateToString = substr($date,0,10); } $initDate = new \DateTime($dateToString);
#begin_debug
#echo "Date from string " . $dateToString . " : " . $initDate->format("d-m-Y") . " (timestamp) " . $initDate->getTimestamp() . "<br />\n";
#end_debug
return new MongoUTCDate($initDate->getTimestamp());
}
我的控制器是这样工作的:
$stats->_id = $this->requestData()->_id;
$stats->purchases = [array(
"date" => \wp\Database\MongoDB\Utilities\MongoDate::toIsoDate($this->requestData()->date),
"coords" => array("lat" => $this->requestData()->coords->lat, "lon" => $this->requestData()->coords->lon),
"metar" => null,
"quantity" => $this->requestData()->quantity,
"price" => (float) $this->requestData()->price,
"peremption" => \wp\Database\MongoDB\Utilities\MongoDate::toIsoDate($this->requestData()->peremption)
)];
$stats->insert();
调用时,文档已正确创建,但日期错误:
{
"_id" : "3256222010007",
"purchases" : [
{
"date" : ISODate("1970-01-18T07:43:01.706Z"),
"coords" : {
"lat" : 43.7294742,
"lon" : 1.416332
},
"metar" : null,
"quantity" : 1,
"price" : 2.87,
"peremption" : ISODate("1970-01-18T22:20:34.800Z")
}
]
}
在前面的例子中,日期就是当天的日期...
当我记录数据时,我看到 PHP 中的日期格式正确:
Date from string 2017-06-04 : 04-06-2017 (timestamp) 1496527200<br />
如果转换回时间戳,得到正确的日期......所以,不明白为什么 Mongo 日期不正确。
【问题讨论】: