- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 } ] }
- Related Articles
- Pull an element in sub of sub-array in MongoDB?
- MongoDB query to pull array element from a collection?
- How to remove an element from a doubly-nested array in a MongoDB document?
- How to pull even numbers from an array in MongoDB?
- Removing an array element from MongoDB collection using update() and $pull
- MongoDB query to pull a specific value from a document
- MongoDB query to add new array element in document
- How to use MongoDB $pull to delete documents within an Array?
- Pull multiple objects from an array in MongoDB?
- How to query a document in MongoDB comparing fields from an array?
- How to add a sub-document to sub-document array in MongoDB?
- How to pull all elements from an array in MongoDB without any condition?
- Add a field to an embedded document in an array in MongoDB?
- How to get the matching document inside an array in MongoDB?
- How to project specific fields from a document inside an array in Mongodb?

Advertisements