MongoDB PHP MongoDate Tricks post

Posted on 2013-07-16 by jwage

Here are a few tricks I’ve learned working with MongoDB and PHP.

Create DateTime from MongoId

Because MongoDB identifiers contain the date you can easily create a DateTime instance from them.

public function getDateTimeFromMongoId(MongoId $mongoId)
    $dateTime = new DateTime('@'.$mongoId->getTimestamp());
    $dateTime->setTimezone(new DateTimeZone(date_default_timezone_get()));
    return $dateTime;

This is useful when you don’t want to create an additional field to store the date a document was created. You can also use the _id index that already exists to paginate and filter/sort by date.

Create MongoId with Date in the Past

For the same reason as above, you can create a MongoId instance with a date in the past. This was copied from a stackoverflow answer by Derek Rethans.

public createMongoIdFromTimestamp($timestamp)
    $ts = pack('N', $timestamp);
    $m = substr(md5(gethostname()), 0, 3);
    $pid = pack('n', posix_getpid());
    $trail = substr(pack('N', $this->inc++), 1, 3);

    $bin = sprintf('%s%s%s%s', $ts, $m, $pid, $trail);

    $id = '';
    for ($i = 0; $i < 12; $i++ ) {
        $id .= sprintf('%02X', ord($bin[$i]));

    return new \MongoID($id);

This was useful when migrating legacy data in to a collection where we utilize the _id for pagination and displaying a created date. If we simply created identifiers with todays date then it would show old records with all the same date and pagination/sorting would be broken.

Categories: articles