MongoDB query to remove subdocument from document?


To remove subdocument from a document, use $pull along with update(). Let us first create a collection with documents −

> db.demo538.insertOne(
... {
...    id:101,
...    "details":
...    {
...       anotherDetails:
...       [
...          {
...             "Name":"Chris",
...             Age:21
...          },
...          {
...             "Name":"David",
...             Age:23
...          },
...          {
...             "Name":"Bob",
...             Age:20
...          }
...       ]
...    }
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8c8f0aef4dcbee04fbbc08")
}

Display all documents from a collection with the help of find() method −

> db.demo538.find();

This will produce the following output −

{ "_id" : ObjectId("5e8c8f0aef4dcbee04fbbc08"), "id" : 101, "details" : { "anotherDetails" : [
   { "Name" : "Chris", "Age" : 21 }, { "Name" : "David", "Age" : 23 }, { "Name" : "Bob", "Age" : 20 } ]
} }

Following is the query to remove subdocument from a document −

> db.demo538.update({ id:101},
... {$pull : { "details.anotherDetails" : {"Age":23} } } )
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Display all documents from a collection with the help of find() method −

> db.demo538.find();

This will produce the following output −

{ "_id" : ObjectId("5e8c8f0aef4dcbee04fbbc08"), "id" : 101, "details" : { "anotherDetails" : [ {
"Name" : "Chris", "Age" : 21 }, { "Name" : "Bob", "Age" : 20 } ] } }

Updated on: 14-May-2020

630 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements