MongoDB में पोजिशनल $ ऑपरेटर के साथ $set का उपयोग करके ऐरे एलिमेंट को रिप्लेस करना
एक ऐरे के अंदर एक विशिष्ट एलिमेंट को अपडेट करने के लिए, क्वेरी से मेल खाने वाले ऐरे एलिमेंट को संदर्भित करने के लिए $set के साथ पोजिशनल $ ऑपरेटर का उपयोग करें।
नमूना डेटा बनाना
> db.replaceValueInArrayDemo.insertOne({"StudentScores":[45,56,78]});
{ "acknowledged" : true, "insertedId" : ObjectId("5cd7f0421a844af18acdffb7") }
> db.replaceValueInArrayDemo.insertOne({"StudentScores":[33,90,67]});
{ "acknowledged" : true, "insertedId" : ObjectId("5cd7f0521a844af18acdffb8") }
सभी डॉक्यूमेंट्स देखना
> db.replaceValueInArrayDemo.find().pretty();
आउटपुट:
{ "_id" : ObjectId("5cd7f0421a844af18acdffb7"), "StudentScores" : [ 45, 56, 78 ] }
{ "_id" : ObjectId("5cd7f0521a844af18acdffb8"), "StudentScores" : [ 33, 90, 67 ] }
ऐरे में मान 45 को 99 से रिप्लेस करना
> db.replaceValueInArrayDemo.update(
{ _id: ObjectId("5cd7f0421a844af18acdffb7"), StudentScores: 45 },
{ $set: { 'StudentScores.$': 99 } }
);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
परिणाम वेरिफाई करना
> db.replaceValueInArrayDemo.find().pretty();
आउटपुट:
{ "_id" : ObjectId("5cd7f0421a844af18acdffb7"), "StudentScores" : [ 99, 56, 78 ] }
{ "_id" : ObjectId("5cd7f0521a844af18acdffb8"), "StudentScores" : [ 33, 90, 67 ] }
व्याख्या
{ _id: ..., StudentScores: 45 }- विशिष्ट डॉक्यूमेंट ढूंढता है और ऐरे में मान 45 वाले एलिमेंट से मेल खाता है।StudentScores.$- पोजिशनल$क्वेरी शर्त (StudentScores: 45) से मेल खाने वाले ऐरे में पहले एलिमेंट को संदर्भित करता है।$set- उस एलिमेंट को नए मान (99) से प्रतिस्थापित करता है।
महत्वपूर्ण सीमाएं
- पोजिशनल
$केवल पहले मिलान करने वाले ऐरे एलिमेंट को अपडेट करता है। - यदि ऐरे में डुप्लिकेट मान हैं (उदाहरण के लिए, [45, 45, 78]), केवल पहला 45 बदल जाता है।
- सभी मिलान करने वाले एलिमेंट्स को अपडेट करने के लिए, MongoDB 3.6+ में
arrayFiltersके साथ फिल्टर्ड पोजिशनल ऑपरेटर$[identifier]का उपयोग करें।
ArrayFilters के साथ आधुनिक दृष्टिकोण (MongoDB 3.6+)
db.collection.updateOne(
{ _id: ObjectId("...") },
{ $set: { "StudentScores.$[elem]": 99 } },
{ arrayFilters: [ { "elem": 45 } ] }
);
यह ऐरे में मान 45 वाले सभी** एलिमेंट्स को अपडेट करता है।