How to Use $currentDate Operator in MongoDB for Date Updates
Use the
$currentDate operator in MongoDB update commands to set a field to the current date or timestamp. It automatically assigns the current date/time to the specified field when the update runs.Syntax
The $currentDate operator is used inside an update command to set a field to the current date or timestamp. You specify the field name and the type of value you want: "date" for a Date object or "timestamp" for a BSON timestamp.
Example syntax:
{ $currentDate: { fieldName: true } }sets the field to the current date.{ $currentDate: { fieldName: { $type: "timestamp" } } }sets the field to the current timestamp.
json
{
$currentDate: {
lastModified: true,
lastAccessed: { $type: "timestamp" }
}
}Example
This example updates a document in the users collection by setting the lastLogin field to the current date and the lastActivity field to the current timestamp.
mongodb
db.users.updateOne(
{ username: "alice" },
{
$currentDate: {
lastLogin: true,
lastActivity: { $type: "timestamp" }
}
}
)Output
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
Common Pitfalls
- Using
$currentDateoutside of an update operation will cause an error. - Setting the value to
falsedoes nothing; usetrueor{ $type: "timestamp" }. - Confusing
"date"and"timestamp"types:"date"stores a JavaScript Date,"timestamp"stores a BSON timestamp used internally by MongoDB.
mongodb
/* Wrong usage: */ db.users.updateOne( { username: "bob" }, { $currentDate: { lastLogin: false } } ) /* Correct usage: */ db.users.updateOne( { username: "bob" }, { $currentDate: { lastLogin: true } } )
Quick Reference
| Usage | Description |
|---|---|
| { $currentDate: { field: true } } | Sets field to current Date object |
| { $currentDate: { field: { $type: "timestamp" } } } | Sets field to current BSON timestamp |
| Used only in update commands | Cannot be used in insert or find operations |
| Field must exist or will be created | Creates the field if it does not exist |
Key Takeaways
Use $currentDate in update commands to set fields to the current date or timestamp automatically.
Specify true for a Date type or { $type: "timestamp" } for a BSON timestamp.
Do not use false or omit $currentDate in updates expecting date changes.
It works only in update operations, not in inserts or queries.
Fields will be created if they do not already exist.