MongoDB $currentDate

In MongoDB, the $currentDate operator sets the value of a field to the current date.

It can be set as either a Date or a timestamp type. The default is Date.

$currentDate is an update operator, and can only be used when updating documents, not when inserting them (although it can be used in upsert operations).

Example

Suppose we have a collection called dogs with the following document:

{
	"_id" : 1,
	"name" : "Wag",
	"goodDog" : true,
	"dateModified" : ISODate("2020-01-01T00:00:00Z")
}

And we want to make a change to the document. When we make the change, we need to update the dateModified field to the date of the change.

Therefore, we can use the $currentDate operator to set the date to the current date. We can do something like this:

db.dogs.update( 
  { _id: 1 }, 
  {
    $currentDate: {
      dateModified: true
    },
    $set: {
      goodDog: false
    }
  }
)

Here, we use dateModified: true to set the date using the Date type (this is a shorthand way of setting it as a Date type).

We can verify the result by looking at the collection/document again:

db.dogs.findOne()

Result:

{
	"_id" : 1,
	"name" : "Wag",
	"goodDog" : false,
	"dateModified" : ISODate("2021-01-16T04:17:41.206Z")
}

We can see that the dateModified field has been updated to the current date (i.e. the date/time that I ran the update). The goodDog field has also been updated as specified.

Timestamps

By default $currentDate uses the Date type. You can alternatively specify the type in a document. Therefore, you can use {$type: timestamp} so that the date is updated to a timestamp BSON type.

Example:

db.dogs.update( 
  { _id: 1 }, 
  {
    $currentDate: {
      dateModified: { $type: "timestamp" }
    },
    $set: {
      goodDog: true
    }
  }
)

In this case, we provided a document that specified the timestamp type.

You can also use this method for the Date type (or use the shorthand method as seen in the previous example).

Check the collection:

db.dogs.findOne()

Result:

{
	"_id" : 1,
	"name" : "Wag",
	"goodDog" : true,
	"dateModified" : Timestamp(1610771023, 1)
}