- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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
MongoDB query to remove item from array?
To remove item from array, you can use $pull operator. Let us create a collection with documents −
> db.removeItemFromArray.insertOne( { "_id":101, "StudentName":"Larry", "StudentSubjects":["C","MongoDB","Java","MySQL"] } ); { "acknowledged" : true, "insertedId" : 101 }
Display all documents from a collection with the help of find() method. The query is as follows −
> db.removeItemFromArray.find().pretty();
This will produce the following output −
{ "_id" : 101, "StudentName" : "Larry", "StudentSubjects" : [ "C", "MongoDB", "Java", "MySQL" ] }
Following is the query to remove item from an array −
> db.removeItemFromArray.update( ... { }, ... { $pull: {StudentSubjects:"Java" } }, ... { multi: true } ... ); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
In the above query, we have removed “Java”. Let us now display the documents from the collection −
> db.removeItemFromArray.find().pretty();
This will produce the following output −
{ "_id" : 101, "StudentName" : "Larry", "StudentSubjects" : [ "C", "MongoDB", "MySQL" ] }
Advertisements