- 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 update array with multiple conditions in MongoDB
To update array with multiple conditions, use $push in MongoDB. Let us create a collection with documents −
> db.demo94.insertOne( ... { ... ... "Details" : [ ... { ... "Name" : "Chris", ... "Subject" : [] ... }, ... { ... "Name" : "David", ... "Subject" : [] ... }, ... { ... "Name" : "Bob", ... "Subject" : [] ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e2d553bb8903cdd865577a9") }
Display all documents from a collection with the help of find() method −
> db.demo94.find();
This will produce the following output −
{ "_id" : ObjectId("5e2d553bb8903cdd865577a9"), "Details" : [ { "Name" : "Chris", "Subject" : [ ] }, { "Name" : "David", "Subject" : [ ] }, { "Name" : "Bob", "Subject" : [ ] } ] }
Following is the query to update array with multiple conditions in MongoDB −
> db.demo94.updateOne( ... { ... ... "Details": { "$elemMatch": { "Name": "David"}} ... }, ... { ... "$push": { "Details.$.Subject": { "Subject": "MongoDB" }} ... } ...); { "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
Display all documents from a collection with the help of find() method −
> db.demo94.find();
This will produce the following output −
{ "_id" : ObjectId("5e2d553bb8903cdd865577a9"), "Details" : [ { "Name" : "Chris", "Subject" : [ ] }, { "Name" : "David", "Subject" : [ { "Subject" : "MongoDB" } ] }, { "Name" : "Bob", "Subject" : [ ] } ] }
Advertisements