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 pull an array element (which is a document) in MongoDB?
You can use $pull operator. Let us first create a collection with documents −
> db.pullAnArrayElementDemo.insertOne( { "StudentDetails": [ { "StudentFirstName":"Chris","StudentScore":56 }, {"StudentFirstName":"Robert","StudentScore":59 } ] } );
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd3b55bedc6604c74817cd5")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.pullAnArrayElementDemo.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5cd3b55bedc6604c74817cd5"),
"StudentDetails" : [
{
"StudentFirstName" : "Chris",
"StudentScore" : 56
},
{
"StudentFirstName" : "Robert",
"StudentScore" : 59
}
]
}
Following is the query to pull an array element (which is a document) in MongoDB −
>db.pullAnArrayElementDemo.update({},{$pull:{'StudentDetails':{'StudentFirstName':'Chris'}}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Let us display all the documents once again. The query is as follows −
> db.pullAnArrayElementDemo.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5cd3b55bedc6604c74817cd5"),
"StudentDetails" : [
{
"StudentFirstName" : "Robert",
"StudentScore" : 59
}
]
}Advertisements