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

Timestamps का उपयोग

MongoDB में कोई automatic created और updated fields नहीं हैं, इसलिए आप dates खुद Date values से store करते हैं।

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

Dates को new Date() या ISODate() से BSON Date values की तरह save करें। server time set करने के लिए updates में $currentDate इस्तेमाल करें, और Mongoose का timestamps option automatically createdAt और updatedAt add करता है। Times को UTC में store करें और display के लिए convert करें।

Note: अगर आपको सिर्फ createdAt चाहिए तो एक ObjectId पहले से creation time encode करता है।

उदाहरण: 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/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. Dates को strings की तरह store करना
  2. database में local time zones इस्तेमाल करना
  3. changes पर updatedAt update करना भूल जाना
चैप्टर सारांश
  • Dates को Date values की तरह store करें
  • ISODate या new Date() इस्तेमाल करें
  • $currentDate server time set करता है
  • UTC में store करें
🔒

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.