I did the update from php 7.2 to 7.4 and I find an unexpected behavior when i store datetime in mongodb
so i try
$client = new MongoDB\Client("mongodb://localhost:27017");
$collection = $client->needToBeDrop->datetime;
$document =[
'name'=>'some date',
'mongo_date'=> new MongoDB\BSON\UTCDateTime(new DateTime()),
'date'=> new DateTime()
];
$result = $collection->insertOne($document);
in php 7.4 i have this result:
{
"name": "some date 7.4",
"mongo_date": {
"$date": 1583845613778
},
"date": {}
}
and in php 7.2 i have
{
"name": "some date 7.2",
"mongo_date": {
"$date": 1583845637335
},
"date": {
"date": "2020-03-10 13:07:17.335813",
"timezone_type": 3,
"timezone": "UTC"
}
}
how i can keep the php 7.2 behavior ?
The problem is related with DateTime object to json serialization. I've tried on PHP 7.4 :
$d = new \DateTime();
echo json_encode(d);
and result is:
{
"date":"2020-08-14 14:33:33.910110",
"timezone_type":3,
"timezone":"UTC"
}
This is same with PHP 7.2 mongodb record. But mongodb extensiton on PHP 7.4 (my mongodb extensiton version is 1.6.1) is not correctly serializing DateTime object. I've refactored my code from
["datetime"=>new \DateTime()]
to
["datetime"=>json_decode(json_encode(new \DateTime()),true)]
Then I tested with sort({"datetime":-1}) method and it's work!
I hope I could help
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With