Insert MongoDB ISODate PHP

Douglas Tober picture Douglas Tober · Dec 24, 2015 · Viewed 7.8k times · Source

I am using the following versions:

PHP                -> 5.6.11  
MongoDB            -> 3.2  
MongoDB PHP Driver -> 1.1

When I was looking to install a MongoDB PHP driver here I noticed that the driver named "Mongo" had been deprecated and proceeded to follow the provided link to install the new extension "MongoDB". This will be referred to as php_mongodb. Since I am using a Windows System I had to copy the file php_mongodb.dll to my ../php/ext and added the line extension=php_mongodb.dll to my PHP.ini

Using the now deprecated driver I used to be able to insert a MongoDate() as shown below.

<?php
    $connection = new MongoClient();
    $database = $connection->selectDB('test');
    $coll = new MongoCollection($database, 'users');

    $coll->insert(
        (object)array(
            "createdAt" => new MongoDate()
        )
    );
?>

The Problem is that with the new php_mongodb this MongoDate() does not seem to be available I receive the error: Fatal error: Class 'MongoDate' not found

  • What is the equivalent to this using new php_mongodb driver?
  • Should I consider downgrading my version of MongoDB to 3.0 so that I can use the now legacy Mongo Driver?
  • Is there a PHP native way to make a date that is of type ISODate?

Should I consider downgrading my version of MongoDB to 3.0 so that I can use the now legacy Mongo Driver?

This is what I've tried to no avail, the following will add a value of type Timestamp to a Document, however it seems that because it is not of type ISODate that I am unable to enforce TTL with this createdAt field:

<?php
    require '/vendor/autoload.php';

    $date = new MongoDB\BSON\Timestamp(1, date('U'));

    $manager = new MongoDB\Driver\Manager("mongodb://127.0.0.1:27017");
    $collection = new MongoDB\Collection($manager, "test.users");
    
    $ex = [
        "createdAt" => $date
    ];
    
    $result = $collection->insertOne( $ex );
?>

Another thing I have tried is the below date, however without the MongoDate() functionality I do not know how to insert this as the type ISODate for MongoDB:
date(DATE_ISO8601, date('U'));

Answer

calvix picture calvix · Jan 25, 2016

not sure if you still need this, but i have been struggling a lot with this. Finally i have been able to figure it out.

$orig_date = new DateTime('2016-01-22  14:00:00');
# or you can use any other way to construct with (int timestamp)
$mongo_date = new MongoDB\BSON\UTCDateTime($orig_date->getTimestamp());
$filter = [
          ....
           ....
            ['timestamp' => ['$gte' =>  $mongo_date]],
           ....
          ....
]
# create command (for example aggregation)
$cmd = new MongoDB\Driver\Command( $filter );
# execute command
$cursor = $manager->executeCommand('my_mongo_db_name', $cmd);

This code works for me.