- 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
How to delete element from an array in MongoDB?
To delete element from an array, use $pull. Let us create a collection with documents −
> db.demo279.insertOne({id:[101,103,105,110]}); { "acknowledged" : true, "insertedId" : ObjectId("5e490af7dd099650a5401a58") } > db.demo279.insertOne({id:[107,111,110]}); { "acknowledged" : true, "insertedId" : ObjectId("5e490b06dd099650a5401a59") }
Display all documents from a collection with the help of find() method −
> db.demo279.find();
This will produce the following output −
{ "_id" : ObjectId("5e490af7dd099650a5401a58"), "id" : [ 101, 103, 105, 110 ] } { "_id" : ObjectId("5e490b06dd099650a5401a59"), "id" : [ 107, 111, 110 ] }
Following is the query to delete element from an array &minus';
> db.demo279.update({},{$pull:{id:110}},{multi:true}); WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })
Display all documents from a collection with the help of find() method −
> db.demo279.find();
This will produce the following output −
{ "_id" : ObjectId("5e490af7dd099650a5401a58"), "id" : [ 101, 103, 105 ] } { "_id" : ObjectId("5e490b06dd099650a5401a59"), "id" : [ 107, 111 ] }
Advertisements