In the MongoDB shell, Date()
and ISODate()
can be used to construct date objects (see: Date() in the shell documentation); however, those functions are unrelated to PHP or its driver. In a subsequent example, I see you used $date
, which appears to be Extended JSON syntax (also unrelated to PHP).
To clear up any misunderstanding, I would suggest you start by familiarizing yourself with the BSON Types in MongoDB. There is a particular BSON type (0x09
) that corresponds to a UTC date time value, which is not to be confused with the Timestamp BSON type (0x11
), which is used internally for things like replication.
In the MongoDB shell, Date()
and ISODate()
can both be used to construct JavaScript objects that will encode as UTC date times in BSON. In the PHP driver, the MongoDB\BSON\UTCDateTime object serves that purpose.
Independent of the MongoDB driver, PHP itself has a DateTime object, which represents a date with a timezone. Since the MongoDB date type assumes a UTC time zone, the PHP driver allows you to construct a UTCDateTime object from a PHP DateTime instance; however, the driver will not automatically convert a PHP DateTime into a BSON date for you. If given a PHP DateTime, the standard rules for encoding PHP objects to BSON will apply (i.e. only its public properties will be saved as document fields).
How to specify a MongoDB ‘new Date()’ when using the PHP driver?
Please review the examples on MongoDB\BSON\UTCDateTime::__construct(), which demonstrate constructing a UTCDateTime instances from an integer, DateTime object, and without arguments.
If you are starting from a date string value, then you’ll always want to review DateTime::__construct() or createFromFormat()
. Since the PHP driver allows construction of a UTCDateTime from a PHP DateTime, it does not reimplement the logic for parsing a date from a string.
This works fine in Composer.
Note that Composer is a package manager. I’m not sure if you meant to refer to the MongoDB PHP Library, which is distributed as a Composer package, but it helps to use to correct terms to avoid any misunderstanding.
Lastly, my replies in mongodb/mongo-php-driver#187 may also be helpful to clear up some misunderstandings. That’s an old issue, but it pertains to some users attempting to use ISODate()
and JSON syntax with the PHP driver.