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
How to use MongoDB $pull to delete documents within an Array?
You need to use update command along with $pull operator to delete documents within an array. Let us create a collection with documents. Following is the query
> db.deleteDocumentsDemo.insertOne(
... {
... "_id":100,
... "StudentsDetails" : [
... {
... "StudentId" : 1,
... "StudentName" : "John"
... },
... {
... "StudentId" : 2,
... "StudentName" : "Carol"
... },
... {
... "StudentId" : 3,
... "StudentName" : "Sam"
... },
... {
... "StudentId" : 4,
... "StudentName" : "Mike"
... }
... ]
... }
...
... );
{ "acknowledged" : true, "insertedId" : 100 }
> db.deleteDocumentsDemo.insertOne(
... {
... "_id":200,
... "StudentsDetails" : [
... {
... "StudentId" : 5,
... "StudentName" : "David"
... },
... {
... "StudentId" : 6,
... "StudentName" : "Ramit"
... },
... {
... "StudentId" : 7,
... "StudentName" : "Adam"
... },
... {
... "StudentId" : 8,
... "StudentName" : "Larry"
... }
... ]
... }
...
... );
{ "acknowledged" : true, "insertedId" : 200 }
Following is the query to display all documents from a collection with the help of find() method
> db.deleteDocumentsDemo.find().pretty();
This will produce the following output
{
"_id" : 100,
"StudentsDetails" : [
{
"StudentId" : 1,
"StudentName" : "John"
},
{
"StudentId" : 2,
"StudentName" : "Carol"
},
{
"StudentId" : 3,
"StudentName" : "Sam"
},
{
"StudentId" : 4,
"StudentName" : "Mike"
}
]
}
{
"_id" : 200,
"StudentsDetails" : [
{
"StudentId" : 5,
"StudentName" : "David"
},
{
"StudentId" : 6,
"StudentName" : "Ramit"
},
{
"StudentId" : 7,
"StudentName" : "Adam"
},
{
"StudentId" : 8,
"StudentName" : "Larry"
}
]
}
Following is the query to delete documents within an array
> db.deleteDocumentsDemo.update({},
... {$pull: {StudentsDetails: {StudentName: "David"}}},
... {multi: true});
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 1 })
Let us check the documents are deleted or not. Following is the query
> db.deleteDocumentsDemo.find().pretty();
This will produce the following output
{
"_id" : 100,
"StudentsDetails" : [
{
"StudentId" : 1,
"StudentName" : "John"
},
{
"StudentId" : 2,
"StudentName" : "Carol"
},
{
"StudentId" : 3,
"StudentName" : "Sam"
},
{
"StudentId" : 4,
"StudentName" : "Mike"
}
]
}
{
"_id" : 200,
"StudentsDetails" : [
{
"StudentId" : 6,
"StudentName" : "Ramit"
},
{
"StudentId" : 7,
"StudentName" : "Adam"
},
{
"StudentId" : 8,
"StudentName" : "Larry"
}
]
}
Look at the above sample output, the “StudentId” with value 5 i.e. StudentName “David” have been deleted.
Advertisements