MongoDB में ऑटो-इन्क्रीमेंट सीक्वेंस के लिए एक अलग कलेक्शन में काउंटर मेंटेन करें और findAndModify का उपयोग करें।
चरण 1: सीक्वेंस कलेक्शन बनाएं
> db.createSequenceDemo.insertOne({_id: "SID", S_Value: 0});
{ "acknowledged": true, "insertedId": "SID" }
चरण 2: नेक्स्ट सीक्वेंस फंक्शन बनाएं
> function nextSequence(s) {
var sd = db.createSequenceDemo.findAndModify({
query: {_id: s},
update: {$inc: {S_Value: 1}},
new: true
});
return sd.S_Value;
}
चरण 3: फंक्शन का उपयोग करके डॉक्यूमेंट इन्सर्ट करें
> db.checkSequenceDemo.insertOne({"StudentId": nextSequence("SID"), "StudentName": "Larry", "StudentMathMarks": 78});
> db.checkSequenceDemo.insertOne({"StudentId": nextSequence("SID"), "StudentName": "Mike", "StudentMathMarks": 89});
> db.checkSequenceDemo.insertOne({"StudentId": nextSequence("SID"), "StudentName": "Sam", "StudentMathMarks": 67});
सभी डॉक्यूमेंट देखने के लिए:
> db.checkSequenceDemo.find().pretty();
आउटपुट:
StudentIdफील्ड ऑटोमेटिकली 1, 2, 3 के रूप में इन्क्रीमेंट हुआ।नोट: प्रोडक्शन में हाई कंकरेंसी के लिए MongoDB 4.2+ में
findOneAndUpdateया डेडिकेटेड सीक्वेंस सर्विस का उपयोग करें।