Timestamps का उपयोग
MongoDB में कोई automatic created और updated fields नहीं हैं, इसलिए आप dates खुद Date values से store करते हैं।
In this page:
Syntax
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
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. #}
आम गलतियां
- Dates को strings की तरह store करना
- database में local time zones इस्तेमाल करना
- 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: