Resolve 'multi update only works with $ operators' in MongoDb?

The "multi update only works with $ operators" error occurs when trying to update multiple documents without using MongoDB's update operators like $set. To resolve this, use update operators when the multi flag is set to true.

Syntax

db.collection.update(
    { /* query */ },
    { $set: { "fieldName": "newValue" } },
    { multi: true }
)

Sample Data

db.unconditionalUpdatesDemo.insertMany([
    { "ClientName": "Larry", "ClientAge": 24 },
    { "ClientName": "Mike", "ClientAge": 26 },
    { "ClientName": "Sam", "ClientAge": 27 },
    { "ClientName": "Carol", "ClientAge": 29 }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5c8eb7372f684a30fbdfd557"),
        ObjectId("5c8eb73f2f684a30fbdfd558"),
        ObjectId("5c8eb7462f684a30fbdfd559"),
        ObjectId("5c8eb7502f684a30fbdfd55a")
    ]
}

Example: Multi-Document Update

Update all documents to change ClientName to "Robert" using the $set operator ?

db.unconditionalUpdatesDemo.update(
    {},
    { $set: { "ClientName": "Robert" } },
    { multi: true }
);
WriteResult({ "nMatched": 4, "nUpserted": 0, "nModified": 4 })

Verify Result

db.unconditionalUpdatesDemo.find();
{
    "_id": ObjectId("5c8eb7372f684a30fbdfd557"),
    "ClientName": "Robert",
    "ClientAge": 24
}
{
    "_id": ObjectId("5c8eb73f2f684a30fbdfd558"),
    "ClientName": "Robert",
    "ClientAge": 26
}
{
    "_id": ObjectId("5c8eb7462f684a30fbdfd559"),
    "ClientName": "Robert",
    "ClientAge": 27
}
{
    "_id": ObjectId("5c8eb7502f684a30fbdfd55a"),
    "ClientName": "Robert",
    "ClientAge": 29
}

Key Points

  • Always use update operators like $set, $inc, or $unset when updating multiple documents.
  • The multi: true option enables updating all matching documents.
  • Without update operators, MongoDB can only update a single document.

Conclusion

Use update operators like $set with the multi flag to update multiple documents. This prevents the "multi update only works with $ operators" error and ensures proper document modification.

Updated on: 2026-03-15T00:12:50+05:30

891 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements