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"
      }
   ]
}

Updated on: 02-Apr-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements