$currentDate
Sets the value of a field to the current date, either as a Date or a timestamp, useful for tracking document modifications.
Syntax
{ $currentDate: { <field1>: <typeSpecification1>, <field2>: <typeSpecification2> } }
Parameters
field
stringrequiredThe name of the field to set to the current date
typeSpecification
objectType specification: true for Date type, { $type: "timestamp" } for timestamp type (default: true)
Examples
Set current date field
Add a lastUpdated field with current date as Date object
Query:
db.stores.updateOne({ "_id": "store-001" }, { $currentDate: { "lastUpdated": true } })
Output:
Updates the document with lastUpdated field containing current date
Set timestamp field
Add both date and timestamp fields for modification tracking
Query:
db.stores.updateOne({ "_id": "store-001" }, { $currentDate: { "lastModified": true, "lastModifiedTimestamp": { $type: "timestamp" } } })
Output:
Updates document with both Date and Timestamp fields