$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

fieldstringrequired

The name of the field to set to the current date

typeSpecificationobject

Type 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

Update nested fields

Set current date for nested fields in document structure

Query:

db.stores.updateOne({ "_id": "store-001" }, { $currentDate: { "sales.lastSalesUpdate": true, "staff.lastStaffUpdate": { $type: "timestamp" } } })

Output:

Updates nested fields with current date and timestamp values

Bulk update with current date

Update multiple documents with current date

Query:

db.stores.updateMany({ "status": "active" }, { $currentDate: { "lastChecked": true } })

Output:

Updates all active stores with current date in lastChecked field

Related