Document से subdocument remove करने के लिए $pull operator का उपयोग update() के साथ करें। आइए पहले documents के साथ एक collection बनाते हैं:
> db.demo538.insertOne(
... {
... id:101,
... "details" :
... {
... anotherDetails:
... [
... {
... "Name":"Chris",
... Age:21
... },
... {
... "Name":"David",
... Age:23
... },
... {
... "Name":"Bob",
... Age:20
... }
... ]
... }
... }
... );
{ "acknowledged" : true, "insertedId" : ObjectId("5e8c8f0aef4dcbee04fbbc08") }
सभी Documents Display करना
> db.demo538.find();
Output:
{ "_id" : ObjectId("5e8c8f0aef4dcbee04fbbc08"), "id" : 101, "details" : { "anotherDetails" : [ { "Name" : "Chris", "Age" : 21 }, { "Name" : "David", "Age" : 23 }, { "Name" : "Bob", "Age" : 20 } ] } }
Subdocument Remove करने का Query
Age 23 वाले subdocument को remove करने के लिए:
> db.demo538.update({ id:101},
... {$pull : { "details.anotherDetails" : {"Age":23} } } )
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Updated Documents Display करना
> db.demo538.find();
Output (David का record remove हो गया):
{ "_id" : ObjectId("5e8c8f0aef4dcbee04fbbc08"), "id" : 101, "details" : { "anotherDetails" : [ { "Name" : "Chris", "Age" : 21 }, { "Name" : "Bob", "Age" : 20 } ] } }
व्याख्या: $pull operator array से उन सभी instances को remove करता है जो specified condition से match करते हैं। यहाँ हमने details.anotherDetails array से Age: 23 वाले object को remove किया।