Is there any Equivalent of NOW() in MongoDB

For new features in MongoDB 4.2. You can use NOW to get the current datetime value.

Use Case: to access the variable, prefix with $$ and enclose in quotes.

db.students.updateOne( { _id: 3 }, [ { $set: { "test3": 98, modified: "$$NOW"} } ] )

Moreover, The CLUSTER_TIME will return the current timestamp value but is only available on replica sets and sharded clusters.


Have been looking into this for a long time, and found out this seems to work:

db.a.findAndModify({
  query: { _id: { $lt: 0 } },
  update: { $currentDate: { dateField: true } },
  upsert: true,
  new: true // optional
});

The idea behind the strange query part is that it always returns 'not found', so it always creates the document (upsert: true), but also, doesn't use that as value for the new inserted document (for example, using { _id: 0 } in the query would actually insert a document with an _id field of value 0).

A similar approach can be taken using bulks:

var aBulk = db.a.initializeUnorderedBulkOp();
aBulk
  .find({ _id: { $lt: 0 } })
  .upsert()
  .updateOne({
    $currentDate: { dateField: true }
  });
aBulk.execute();

On an insert if you insert a BsonTimeStamp(0,0) in one of the first 2 fields the server will replace with the current timestamp on the server.

$ts = new MongoTimestamp(0, 0);
$document = array("_id" => 1, "s" => 1, "ts" => $ts);
$coll->insert($document);
$document = array("_id" => 2, "ts" => $ts, "s" => 2);
$coll->insert($document);
$document = array("ts" => $ts, "_id" => 3, "s" => 3);
$coll->insert($document);

Documents with _id 2 and 3 will have the current timestamp inserted into the ts field.

> db.timestamp.find()
{ "_id" : 1, "s" : 1, "ts" : Timestamp(0, 0) }
{ "_id" : 2, "ts" : Timestamp(1387236748, 1), "s" : 2 }
{ "_id" : 3, "ts" : Timestamp(1387236748, 2), "s" : 3 }

Also with the server 2.5.3 (to be released as 2.6) you have a new $currentDate update modified (https://jira.mongodb.org/browse/SERVER-10911) that can be used to set a field to a date or timestamp


Getting timestamp of document creation

If you are using MongoDB's default ObjectIDs for your _id field, these include a timestamp component which you can use to infer the creation date for a document. The PHP driver includes a MongoId::getTimestamp() method that can be used to extract the time from an ObjectID.

Note that the ObjectID is normally generated by the PHP driver (not the MongoDB server) so it is important to have your clocks in sync with ntpd or similar if timestamp accuracy is important.

Updating date/timestamps

In the upcoming MongoDB 2.6 release, a new $currentDate update modifier has been added which supports setting server-side dates and timestamps. For more information see: SERVER-10911 in the MongoDB Jira issue tracker.

Until this server-side support is available, your best approach for adding current date/time would be to set in your application code using time() or an equivalent function.

Tags:

Mongodb