- 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
Update multiple elements in an array in MongoDB?
To update multiple elements, use $[]. The $[] is an all positional operator indicating that the update operator should modify all elements in the specified array field.
Let us first create a collection with documents −
> db.demo385.insertOne({"ServerLogs": [ ... { ... "status":"InActive" ... }, ... { ... "status":"InActive" ... }, ... { ... "status":"InActive" ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e5b6a7522064be7ab44e7f5") }
Display all documents from a collection with the help of find() method −
> db.demo385.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e5b6a7522064be7ab44e7f5"), "ServerLogs" : [ { "status" : "InActive" }, { "status" : "InActive" }, { "status" : "InActive" } ] }
Following is the query to update multiple elements in an array in MongoDB −
> db.demo385.update( ... { "_id" : ObjectId("5e5b6a7522064be7ab44e7f5") }, ... { "$set": { "ServerLogs.$[].status": "Active" }} ... ) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo385.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e5b6a7522064be7ab44e7f5"), "ServerLogs" : [ { "status" : "Active" }, { "status" : "Active" }, { "status" : "Active" } ] }
Advertisements