MongoDB में एम्बेडेड फ़ील्ड को इंक्रीमेंट करना
MongoDB में नेस्टेड या एम्बेडेड डॉक्यूमेंट के अंदर मौजूद किसी फ़ील्ड की वैल्यू को बढ़ाने के लिए $inc ऑपरेटर का उपयोग डॉट नोटेशन (.) के साथ किया जाता है।
उदाहरण: स्टूडेंट स्कोर अपडेट करना
मान लीजिए हमारे पास StudentDetails के अंदर StudentScores एम्बेडेड है:
{
"StudentDetails": {
"StudentScores": {
"StudentMathScore": 90,
"StudentMongoDBScore": 78
}
}
}
कलेक्शन बनाएं और डॉक्यूमेंट इन्सर्ट करें
> db.embeddedValueIncrementDemo.insertOne({
"StudentDetails": {
"StudentScores": {
"StudentMathScore": 90,
"StudentMongoDBScore": 78
}
}
});
{
"acknowledged": true,
"insertedId": ObjectId("5cd2b670345990cee87fd896")
}
डॉक्यूमेंट देखें
> db.embeddedValueIncrementDemo.find().pretty();
{
"_id": ObjectId("5cd2b670345990cee87fd896"),
"StudentDetails": {
"StudentScores": {
"StudentMathScore": 90,
"StudentMongoDBScore": 78
}
}
}
एम्बेडेड फ़ील्ड को इंक्रीमेंट करें
StudentMongoDBScore को 20 से बढ़ाने के लिए:
> db.embeddedValueIncrementDemo.update(
{ _id: new ObjectId("5cd2b670345990cee87fd896") },
{ $inc: { "StudentDetails.StudentScores.StudentMongoDBScore": 20 } },
{ upsert: true, safe: true }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
अपडेटेड डॉक्यूमेंट चेक करें
> db.embeddedValueIncrementDemo.find().pretty();
{
"_id": ObjectId("5cd2b670345990cee87fd896"),
"StudentDetails": {
"StudentScores": {
"StudentMathScore": 90,
"StudentMongoDBScore": 98
}
}
}
मुख्य बिंदु
- डॉट नोटेशन (
StudentDetails.StudentScores.StudentMongoDBScore) से नेस्टेड फ़ील्ड तक पहुँचें $incऑपरेटर वैल्यू को एटॉमिक तरीके से बढ़ाता हैupsert: trueसे डॉक्यूमेंट न होने पर नया बन जाता है