MongoDB में केवल एक मान को अपडेट और इंक्रीमेंट करने के लिए update() के साथ $inc का उपयोग करें। आइए एक कलेक्शन बनाते हैं:
> db.demo698.insertOne({Score:78}); { "acknowledged" : true, "insertedId" : ObjectId("5ea6d8a4551299a9f98c9398") }
> db.demo698.insertOne({Score:56}); { "acknowledged" : true, "insertedId" : ObjectId("5ea6d8a7551299a9f98c9399") }
> db.demo698.insertOne({Score:65}); { "acknowledged" : true, "insertedId" : ObjectId("5ea6d8aa551299a9f98c939a") }
> db.demo698.insertOne({Score:88}); { "acknowledged" : true, "insertedId" : ObjectId("5ea6d8b0551299a9f98c939b") }
find() से सभी डॉक्यूमेंट्स देखें:
> db.demo698.find();
आउटपुट:
{ "_id" : ObjectId("5ea6d8a4551299a9f98c9398"), "Score" : 78 }
{ "_id" : ObjectId("5ea6d8a7551299a9f98c9399"), "Score" : 56 }
{ "_id" : ObjectId("5ea6d8aa551299a9f98c939a"), "Score" : 65 }
{ "_id" : ObjectId("5ea6d8b0551299a9f98c939b"), "Score" : 88 }
केवल एक मान को इंक्रीमेंट करने के लिए क्वेरी:
> db.demo698.update({_id:ObjectId("5ea6d8b0551299a9f98c939b")},{$inc:{Score:12}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
find() से सभी डॉक्यूमेंट्स देखें:
> db.demo698.find();
परिणाम:
{ "_id" : ObjectId("5ea6d8a4551299a9f98c9398"), "Score" : 78 }
{ "_id" : ObjectId("5ea6d8a7551299a9f98c9399"), "Score" : 56 }
{ "_id" : ObjectId("5ea6d8aa551299a9f98c939a"), "Score" : 65 }
{ "_id" : ObjectId("5ea6d8b0551299a9f98c939b"), "Score" : 100 }