आप इसके लिए $set ऑपरेटर का उपयोग कर सकते हैं। आइए पहले दस्तावेजों के साथ एक संग्रह बनाएं -
> db.pullAllElementDemo.insertOne(
... {
... "StudentId":101,
... "StudentDetails" : [
... {
...
... "StudentName": "Carol",
... "StudentAge":21,
... "StudentCountryName":"US"
... },
... {
... "StudentName": "Chris",
... "StudentAge":24,
... "StudentCountryName":"AUS"
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5ccdd9c8685b30d09a7111e4")
}
> db.pullAllElementDemo.insertOne(
... {
... "StudentId":102,
... "StudentDetails" : [
... {
...
... "StudentName": "Robert",
... "StudentAge":27,
... "StudentCountryName":"UK"
... },
... {
... "StudentName": "David",
... "StudentAge":23,
... "StudentCountryName":"US"
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5ccdd9f7685b30d09a7111e5")
} खोज () विधि की मदद से संग्रह से सभी दस्तावेजों को प्रदर्शित करने के लिए क्वेरी निम्नलिखित है -
> db.pullAllElementDemo.find().pretty();
यह निम्नलिखित आउटपुट देगा -
{
"_id" : ObjectId("5ccdd9c8685b30d09a7111e4"),
"StudentId" : 101,
"StudentDetails" : [
{
"StudentName" : "Carol",
"StudentAge" : 21,
"StudentCountryName" : "US"
},
{
"StudentName" : "Chris",
"StudentAge" : 24,
"StudentCountryName" : "AUS"
}
]
}
{
"_id" : ObjectId("5ccdd9f7685b30d09a7111e5"),
"StudentId" : 102,
"StudentDetails" : [
{
"StudentName" : "Robert",
"StudentAge" : 27,
"StudentCountryName" : "UK"
},
{
"StudentName" : "David",
"StudentAge" : 23,
"StudentCountryName" : "US"
}
]
} बिना किसी शर्त के MongoDB में सरणी से सभी तत्वों को खींचने की क्वेरी निम्नलिखित है। यहां, हमने $set -
. का उपयोग करके StudentId 102 के साथ StudentDetails को हटा दिया है> db.pullAllElementDemo.update( {StudentId:102}, { "$set": { "StudentDetails": [] }} );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) आइए उपरोक्त संग्रह से सभी दस्तावेजों को प्रदर्शित करें ताकि यह जांचा जा सके कि किसी सरणी से उन विशिष्ट तत्वों को निकाला गया है या नहीं -
> db.pullAllElementDemo.find().pretty();
यह निम्नलिखित आउटपुट देगा -
{
"_id" : ObjectId("5ccdd9c8685b30d09a7111e4"),
"StudentId" : 101,
"StudentDetails" : [
{
"StudentName" : "Carol",
"StudentAge" : 21,
"StudentCountryName" : "US"
},
{
"StudentName" : "Chris",
"StudentAge" : 24,
"StudentCountryName" : "AUS"
}
]
}
{
"_id" : ObjectId("5ccdd9f7685b30d09a7111e5"),
"StudentId" : 102,
"StudentDetails" : [ ]
}