Not able to perform “$$NOW” variable to get date time value on MongoDB 4.2 version

db.getCollection(‘students’).save( { “timeStamp”: “$NOW”,“test”:“fdsfds”})

Hello, @kishan_agarwal! Welcome to the community!

$$NOW is an aggregation variable, which means that it can by used only within aggregation pipeline.

Due to the documentation, save() method is deprecated. use insertOne() instead.

To insert current date you need to provide date value on the client side.
For example, ISODate() function:

const date = ISODate();
db.test.insertOne({ d: date });

Or using javascript Date constructor:

const date = new Date();
db.test.insertOne({ d: date });

You can extract current date from newly constructed ObjectId value:

const date = ObjectId().getTimestamp();
db.test.insertOne({ d: date });

It is possible to set date value on the MongoDB server’s side, using update operations.

So, you can use $$NOW when you update one or more documents using pipeline:

db.test.updateOne({ _id: <ID> }, [{ $set: { d: '$$NOW' } }]);

Or, by updating documents using $currentDate operator:

db.test.updateOne({ _id: <ID> }, { $currentDate: { d: { $type: 'date' } } });

It is possible, to insert documents using update operations using workaround:

  • use range query what will not match any documents in the collection
  • add { usert: true } flag in update operation options
db.test.updateOne({ _id: { $lt: 0 } }, [{ $set: { d: '$$NOW' } }], { upsert: true });

Although the above workaround will work, avoid doing so, because

  • it slower, than insert operators, because before insert it needs to make sure that document does not exist;
  • it may be confusing for other developers

So, prefer insertOne with dates, generated on the app (client) side.

3 Likes

Hi Slava!

Is it possible in never versions to insert a document with a server side timestamp without using an upsert based workaround?