

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 array elements from a document?
Use the $pull to remove array elements from a MongoDB document as shown in the following syntax −
db.yourCollectionName.update( { },{ $pull: { yourFieldName: yourValue }},{multi:true });
Let us first create a collection with documents −
>db.removeArrayElementsDemo.insertOne({"AllPlayerName":["John","Sam","Carol","David"]}); { "acknowledged" : true, "insertedId" : ObjectId("5cd90d011a844af18acdffc1") } >db.removeArrayElementsDemo.insertOne({"AllPlayerName":["Chris","Robert","John","Mike"]}); { "acknowledged" : true, "insertedId" : ObjectId("5cd90d2e1a844af18acdffc2") }
Following is the query to display all documents from a collection with the help of find() method −
> db.removeArrayElementsDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cd90d011a844af18acdffc1"), "AllPlayerName" : [ "John", "Sam", "Carol", "David" ] } { "_id" : ObjectId("5cd90d2e1a844af18acdffc2"), "AllPlayerName" : [ "Chris", "Robert", "John", "Mike" ] }
Here is the query to remove array elements from a document −
> db.removeArrayElementsDemo.update( { },{ $pull: { AllPlayerName: "John" }},{multi:true }); WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })
Let us check all the documents once again −
> db.removeArrayElementsDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cd90d011a844af18acdffc1"), "AllPlayerName" : [ "Sam", "Carol", "David" ] } { "_id" : ObjectId("5cd90d2e1a844af18acdffc2"), "AllPlayerName" : [ "Chris", "Robert", "Mike" ] }
- Related Questions & Answers
- MongoDB query to remove subdocument from document?
- MongoDB query to remove a specific document
- MongoDB query to remove item from array?
- MongoDB query to remove entire array from collection?
- How to query a document in MongoDB comparing fields from an array?
- How to remove a field completely from a MongoDB document?
- MongoDB query to update a specific document from a collection
- MongoDB query to pull a specific value from a document
- How to remove an element from a doubly-nested array in a MongoDB document?
- MongoDB query to match and remove element from an array?
- MongoDB query to remove element from array as sub property
- MongoDB query to push document into an array
- MongoDB Aggregate to get average from document and of array elements?
- How do I remove a string from an array in a MongoDB document?
- Remove values from a matrix like document in MongoDB
Advertisements