Update all the values of a field with a specific string in MongoDB?

To update all the values of a field with a specific string in MongoDB, use the update() method with an empty filter and the multi: true option to affect all documents in the collection.

Syntax

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

Sample Data

db.demo720.insertMany([
    { "SubjectName": "MySQL" },
    { "SubjectName": "Java" },
    { "SubjectName": "C" },
    { "SubjectName": "C++" }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5eaae7ca43417811278f5883"),
        ObjectId("5eaae7ce43417811278f5884"),
        ObjectId("5eaae7d143417811278f5885"),
        ObjectId("5eaae7d543417811278f5886")
    ]
}

Display all documents to verify the initial data ?

db.demo720.find();
{ "_id": ObjectId("5eaae7ca43417811278f5883"), "SubjectName": "MySQL" }
{ "_id": ObjectId("5eaae7ce43417811278f5884"), "SubjectName": "Java" }
{ "_id": ObjectId("5eaae7d143417811278f5885"), "SubjectName": "C" }
{ "_id": ObjectId("5eaae7d543417811278f5886"), "SubjectName": "C++" }

Example: Update All SubjectName Values

Update all documents to set "SubjectName" field to "MongoDB" ?

db.demo720.update(
    {},
    { $set: { SubjectName: "MongoDB" } },
    { multi: true }
);
WriteResult({ "nMatched": 4, "nUpserted": 0, "nModified": 4 })

Verify the update by displaying all documents ?

db.demo720.find();
{ "_id": ObjectId("5eaae7ca43417811278f5883"), "SubjectName": "MongoDB" }
{ "_id": ObjectId("5eaae7ce43417811278f5884"), "SubjectName": "MongoDB" }
{ "_id": ObjectId("5eaae7d143417811278f5885"), "SubjectName": "MongoDB" }
{ "_id": ObjectId("5eaae7d543417811278f5886"), "SubjectName": "MongoDB" }

Key Points

  • Empty filter {} matches all documents in the collection.
  • $set operator updates the specified field with the new value.
  • multi: true option ensures all matching documents are updated, not just the first one.

Conclusion

Use update() with an empty filter and multi: true to efficiently update a field across all documents in a collection. The $set operator replaces the field value while preserving the document structure.

Updated on: 2026-03-15T03:50:36+05:30

324 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements