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 match and remove element from an array?
To match and remove element(s) , use MongoDB $pullAll. Let us first create a collection with documents −
> db.removeElementsDemo.insertOne({"ListOfNames":["Mike","Sam","David","Carol"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e071e5a25ddae1f53b62203")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.removeElementsDemo.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5e071e5a25ddae1f53b62203"),
"ListOfNames" : [
"Mike",
"Sam",
"David",
"Carol"
]
}
Here is the query to match and remove element(s) from an array −
> db.removeElementsDemo.update(
... { },
... {
... $pullAll:
... {
... "ListOfNames": ["Carol"]
... }
... }
... );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Following is the query to display all documents from a collection with the help of find() method −
> db.removeElementsDemo.find().pretty();
This will produce the following output. Above, we removed only a single value −
{
"_id" : ObjectId("5e071e5a25ddae1f53b62203"),
"ListOfNames" : [
"Mike",
"Sam",
"David"
]
}Advertisements