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 remove a specific element from array in MongoDB?
To remove a specific element, use $pull. Let us create a collection with documents −
> db.demo125.insertOne({"ListOfNames":["John","Chris","Bob","David","Carol"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e2f304068e7f832db1a7f55")
}
Display all documents from a collection with the help of find() method −
> db.demo125.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5e2f304068e7f832db1a7f55"),
"ListOfNames" : [
"John",
"Chris",
"Bob",
"David",
"Carol"
]
}
Following is the query to remove a specific element from array in MongoDB −
> db.demo125.update(
... { },
... { $pull: { ListOfNames: { $in: [ "David"] }} },
... { multi: true }
... )
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo125.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5e2f304068e7f832db1a7f55"),
"ListOfNames" : [
"John",
"Chris",
"Bob",
"Carol"
]
}Advertisements