Update multiple elements in an array in MongoDB?

To update multiple elements in an array in MongoDB, use the $[] all positional operator. This operator modifies all elements in the specified array field that match the update criteria.

Syntax

db.collection.update(
    { "matchCondition": "value" },
    { $set: { "arrayField.$[]": "newValue" } }
);

Sample Data

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 the collection ?

db.demo385.find().pretty();
{
    "_id": ObjectId("5e5b6a7522064be7ab44e7f5"),
    "ServerLogs": [
        {
            "status": "InActive"
        },
        {
            "status": "InActive"
        },
        {
            "status": "InActive"
        }
    ]
}

Example: Update All Array Elements

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 })

Verify Result

Display all documents to verify the update ?

db.demo385.find().pretty();
{
    "_id": ObjectId("5e5b6a7522064be7ab44e7f5"),
    "ServerLogs": [
        {
            "status": "Active"
        },
        {
            "status": "Active"
        },
        {
            "status": "Active"
        }
    ]
}

Key Points

  • The $[] operator updates all array elements regardless of their current values.
  • Use $[<identifier>] with arrayFilters for conditional updates on specific elements.
  • The update affects the entire array field in the matched document.

Conclusion

The $[] all positional operator provides an efficient way to update multiple array elements simultaneously. It's ideal when you need to apply the same modification to every element in an array.

Updated on: 2026-03-15T02:45:55+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements