$currentDate (Current Date)
Last updated: 2026-10-09
$currentDate (Current Date)
$currentDate sets a field to the current time as a Date or Timestamp. `{ $currentDate: { lastModified: true } }` stores a Date by default; `{ $currentDate: { lastModified: { $type: 'timestamp' } } }` stores a Timestamp. More precise than client-side new Date() and avoids server/client clock skew.
| Category | Update Field |
|---|---|
| MongoDB Version | 3.6+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $currentDate: { <field>: true | { $type: 'timestamp' | 'date' } } }
⚙️ Parameters
| field | The field to set to the current time. |
|---|---|
| type | true stores a Date; 'timestamp' or 'date' can be explicit. |
Returns:The update result
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $currentDate: record modification time
// true stores a Date by default
db.articles.updateOne(
{ _id: 1 },
{ $currentDate: { lastModified: true } }
)
// Explicit Timestamp
db.articles.updateOne(
{ _id: 1 },
{ $currentDate: { lastModified: { $type: 'timestamp' } } }
)
Output:
// lastModified is set to the server time as Date or Timestamp
📌 Notes
- Creates the field if missing
- Timestamp suits sorting or duplicate-timestamp needs
- Uses server time, independent of client timezones
🏷️ Related Tags
💡 Related Cases
📚 Related Tutorials
❓ FAQ
QWhat is the difference between $currentDate and $set: new Date()?
A$currentDate reads the server clock consistently; $set uses client time, which can differ across clients.
QCan it store a Timestamp?
AYes, specify { $type: 'timestamp' }.
QDoes $currentDate overwrite existing values?
AYes, it overwrites with the current time.