MongoDB दस्तावेज़ से सरणी तत्व हटाने के लिए $pull ऑपरेटर का उपयोग करें। यह ऑपरेटर निर्दिष्ट मान से मेल खाने वाले सभी तत्वों को सरणी से हटा देता है।
सिंटैक्स
db.yourCollectionName.update(
{ },
{ $pull: { yourFieldName: yourValue }},
{multi: true}
);
उदाहरण
कलेक्शन बनाएं और डेटा डालें:
> db.removeArrayElementsDemo.insertOne({"AllPlayerName":["John","Sam","Carol","David"]});
{ "acknowledged" : true, "insertedId" : ObjectId("5cd90d011a844af18acdffc1") }
> db.removeArrayElementsDemo.insertOne({"AllPlayerName":["Chris","Robert","John","Mike"]});
{ "acknowledged" : true, "insertedId" : ObjectId("5cd90d2e1a844af18acdffc2") }
दस्तावेज़ देखने के लिए:
> db.removeArrayElementsDemo.find().pretty();
आउटपुट:
{ "_id" : ObjectId("5cd90d011a844af18acdffc1"), "AllPlayerName" : [ "John", "Sam", "Carol", "David" ] }
{ "_id" : ObjectId("5cd90d2e1a844af18acdffc2"), "AllPlayerName" : [ "Chris", "Robert", "John", "Mike" ] }
"John" को सभी दस्तावेज़ों से हटाएं
> db.removeArrayElementsDemo.update(
{ },
{ $pull: { AllPlayerName: "John" }},
{multi: true}
);
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })
परिणाम जांचें:
> db.removeArrayElementsDemo.find().pretty();
आउटपुट:
{ "_id" : ObjectId("5cd90d011a844af18acdffc1"), "AllPlayerName" : [ "Sam", "Carol", "David" ] }
{ "_id" : ObjectId("5cd90d2e1a844af18acdffc2"), "AllPlayerName" : [ "Chris", "Robert", "Mike" ] }
महत्वपूर्ण: multi: true विकल्प सभी मिलान करने वाले दस्तावेज़ों को अपडेट करता है। MongoDB 3.2+ में updateMany() का उपयोग करना अधिक बेहतर है।