Timestamps
MongoDB has no automatic created and updated fields, so you store dates yourself with Date values.
In this page:
Syntax
db.collection_name.insertOne({ field: value, createdAt: new Date() })
db.collection_name.updateOne(filter, { $currentDate: { updatedAt: true } })
Timestamps
Save dates as BSON Date values with new Date() or ISODate(). Use $currentDate in updates to set the server time, and Mongoose's timestamps option adds createdAt and updatedAt automatically. Store times in UTC and convert for display.
Note:
An ObjectId already encodes the creation time if you only need createdAt.
Example: Timestamps
test> db.posts.insertOne({ _id: 1, title: "Hello", createdAt: new Date("2024-01-05T10:00:00Z") })
{ acknowledged: true, insertedId: 1 }
test> db.posts.updateOne({ _id: 1 }, { $set: { title: "Hello!" }, $currentDate: { updatedAt: true } })
{ acknowledged: true, matchedCount: 1, modifiedCount: 1 }
test> db.posts.findOne({ _id: 1 }, { updatedAt: { $type: "date" } })
{ _id: 1, updatedAt: true }
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Storing dates as strings
- Using local time zones in the database
- Forgetting to update updatedAt on changes
Chapter Summary
- Store dates as Date values
- Use ISODate or new Date()
- $currentDate sets server time
- Store in UTC
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: