MongoDB provides the NOW
system variable that allows you to get the current datetime value when using an aggregation pipeline.
This can be useful for when you want to update a document with the current datetime.
Starting in MongoDB 4.2, update methods can can accept an aggregation pipeline. Therefore, NOW
can be used as an alternative to the $currentDate
field update operator for setting the current datetime when using any of the update methods.
To access the NOW
system variable, prefix it with two dollar signs and surround it in quotes ("$$NOW"
).
Example
Suppose we have a collection called dogs
that contains the following document:
{ "_id" : 1, "name" : "Fetch", "weight" : 25 }
Here’s an example of using the NOW
system variable when updating that document:
db.dogs.updateOne(
{ _id : 1 },
[
{ $set : { weight : 30, lastModified : "$$NOW" } }
]
)
Now let’s take a look at the document again:
db.dogs.find( { _id: 1 } ).pretty()
Result:
{ "_id" : 1, "name" : "Fetch", "weight" : 30, "lastModified" : ISODate("2021-01-27T01:29:32.833Z") }
The lastModified
field has been added with a Date object that contains the current date and time.
There’s also a CLUSTER_TIME
system variable that returns the current timestamp, although this is only available on replica sets and sharded clusters.
Also note that the NOW
and CLUSTER_TIME
values remain the same throughout the pipeline.