← Back to MongoDB Course | Chapter 2: CRUD — Create | Lesson 5 of 7

Timestamps

MongoDB has no automatic created and updated fields, so you store dates yourself with Date values.

In this page:

  1. Timestamps
Syntax
javascript
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

bash
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
  1. Storing dates as strings
  2. Using local time zones in the database
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.