MongoDB में पोजिशनल $ ऑपरेटर का उपयोग करके ऐरे में नेस्टेड ऑब्जेक्ट अपडेट करना
MongoDB में किसी ऐरे के भीतर विशिष्ट की के आधार पर ऑब्जेक्ट को खोजकर उसके फील्ड को अपडेट करने के लिए पोजिशनल $ ऑपरेटर का उपयोग करें।
उदाहरण: संग्रह और दस्तावेज़ बनाना
> db.demo419.insertOne({
"ProductInformation":[
{"ProductName":"Product-1","ProductPrice":500},
{"ProductName":"Product-2","ProductPrice":600}
]
});
{ "acknowledged" : true, "insertedId" : ObjectId("5e724762b912067e57771ae8") }
दस्तावेज़ देखना
> db.demo419.find();
आउटपुट:
{ "_id" : ObjectId("5e724762b912067e57771ae8"), "ProductInformation" : [ { "ProductName" : "Product-1", "ProductPrice" : 500 }, { "ProductName" : "Product-2", "ProductPrice" : 600 } ] }
ProductName "Product-1" वाले ऑब्जेक्ट की कीमत अपडेट करना
> db.demo419.update(
{'ProductInformation.ProductName' : "Product-1" },
{ $set : { 'ProductInformation.$.ProductPrice' : 1250 }}
);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
अपडेट के बाद दस्तावेज़ देखना
> db.demo419.find();
आउटपुट:
{ "_id" : ObjectId("5e724762b912067e57771ae8"), "ProductInformation" : [ { "ProductName" : "Product-1", "ProductPrice" : 1250 }, { "ProductName" : "Product-2", "ProductPrice" : 600 } ] }
व्याख्या:
'ProductInformation.ProductName' : "Product-1"- ऐरे में इस नाम वाला ऑब्जेक्ट खोजेंProductInformation.$.ProductPrice-$मेल खाने वाले ऐरे एलिमेंट की स्थिति को संदर्भित करता है- केवल पहला मेल खाने वाला एलिमेंट अपडेट होता है
एकाधिक मेल खाने वाले एलिमेंट्स अपडेट करने के लिए (MongoDB 3.6+):
db.demo419.updateMany(
{},
{ $set: { "ProductInformation.$[elem].ProductPrice": 1250 } },
{ arrayFilters: [ { "elem.ProductName": "Product-1" } ] }
)
arrayFilters लाभ:
- एक ही ऑपरेशन में सभी मेल खाने वाले एलिमेंट्स अपडेट
- जटिल शर्तें समर्थित
- बेहतर पठनीयता