
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 Pull Array Element from a Collection
Use the $pull operator to pull array element from a collection. Let us first create a collection with documents −
> db.pullElementFromAnArrayDemo.insertOne( ... { ... "StudentScores":[89,56,78,90] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5cd0104a588d4a6447b2e063") }
Following is the query to display all documents from a collection with the help of find() method −
> db.pullElementFromAnArrayDemo.find();
This will produce the following output −
{ "_id" : ObjectId("5cd0104a588d4a6447b2e063"), "StudentScores" : [ 89, 56, 78, 90 ] }
Following is the query to pull array element from a collection. Here, we are removing element 78 −
> db.pullElementFromAnArrayDemo.update({},{ $pull: { StudentScores: 78 } }); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Let us check the document once again −
> db.pullElementFromAnArrayDemo.find();
This will produce the following output −
{ "_id" : ObjectId("5cd0104a588d4a6447b2e063"), "StudentScores" : [ 89, 56, 90 ] }
Advertisements