MongoDB में कंडीशनल $inc: केवल निश्चित वैल्यू से कम पर इंक्रीमेंट
update() में क्वेरी कंडीशन के साथ $inc उपयोग करके केवल उन्हीं डॉक्यूमेंट को इंक्रीमेंट करें जो शर्त पूरी करते हैं।
सिंटैक्स
db.collection.update(
{ field: { $lt: threshold } },
{ $inc: { field: incrementValue } },
false, // upsert
true // multi
);
कलेक्शन बनाएं और डॉक्यूमेंट इन्सर्ट करें
> db.limitIncrementDemo.insertOne({"StudentId":101,"StudentScore":95});
{ "acknowledged": true, "insertedId": ObjectId("5cd2ce9eb64f4b851c3a13c3") }
> db.limitIncrementDemo.insertOne({"StudentId":102,"StudentScore":55});
{ "acknowledged": true, "insertedId": ObjectId("5cd2cea0b64f4b851c3a13c4") }
> db.limitIncrementDemo.insertOne({"StudentId":103,"StudentScore":67});
{ "acknowledged": true, "insertedId": ObjectId("5cd2cea1b64f4b851c3a13c5") }
> db.limitIncrementDemo.insertOne({"StudentId":104,"StudentScore":56});
{ "acknowledged": true, "insertedId": ObjectId("5cd2cea3b64f4b851c3a13c6") }
> db.limitIncrementDemo.insertOne({"StudentId":105,"StudentScore":79});
{ "acknowledged": true, "insertedId": ObjectId("5cd2cea4b64f4b851c3a13c7") }
सभी डॉक्यूमेंट देखें
> db.limitIncrementDemo.find().pretty();
{ "_id": ObjectId("5cd2ce9eb64f4b851c3a13c3"), "StudentId": 101, "StudentScore": 95 }
{ "_id": ObjectId("5cd2cea0b64f4b851c3a13c4"), "StudentId": 102, "StudentScore": 55 }
{ "_id": ObjectId("5cd2cea1b64f4b851c3a13c5"), "StudentId": 103, "StudentScore": 67 }
{ "_id": ObjectId("5cd2cea3b64f4b851c3a13c6"), "StudentId": 104, "StudentScore": 56 }
{ "_id": ObjectId("5cd2cea4b64f4b851c3a13c7"), "StudentId": 105, "StudentScore": 79 }
स्कोर 75 से कम वालों को 10 से बढ़ाएं
> db.limitIncrementDemo.update(
{ StudentScore: { $lt: 75 } },
{ $inc: { StudentScore: 10 } },
false, // upsert: false
true // multi: true (सभी मैचिंग)
);
WriteResult({ "nMatched": 3, "nUpserted": 0, "nModified": 3 })
अपडेट के बाद चेक करें
> db.limitIncrementDemo.find().pretty();
{ "_id": ObjectId("5cd2ce9eb64f4b851c3a13c3"), "StudentId": 101, "StudentScore": 95 } // 95 >= 75, कोई बदलाव नहीं
{ "_id": ObjectId("5cd2cea0b64f4b851c3a13c4"), "StudentId": 102, "StudentScore": 65 } // 55 + 10
{ "_id": ObjectId("5cd2cea1b64f4b851c3a13c5"), "StudentId": 103, "StudentScore": 77 } // 67 + 10
{ "_id": ObjectId("5cd2cea3b64f4b851c3a13c6"), "StudentId": 104, "StudentScore": 66 } // 56 + 10
{ "_id": ObjectId("5cd2cea4b64f4b851c3a13c7"), "StudentId": 105, "StudentScore": 79 } // 79 >= 75, कोई बदलाव नहीं
नोट
multi: true(चौथा पैरामीटर) से सभी मैचिंग डॉक्यूमेंट अपडेट होते हैं- आधुनिक सिंटैक्स:
updateMany({StudentScore: {$lt: 75}}, {$inc: {StudentScore: 10}}) - यह हार्ड लिमिट नहीं है, बल्कि कंडीशनल इंक्रीमेंट है