Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 } ] } }Advertisements