What is the fastest way to update the whole document (all fields) in MongoDB?

The fastest way to update the whole document (all fields) in MongoDB is to use replaceOne() method. This method replaces the entire document while preserving the _id field.

Syntax

db.collection.replaceOne(
    { filter },
    { newDocument }
);

Sample Data

db.demo431.insertMany([
    {"Name": "Chris", "Age": 32},
    {"Name": "David", "Age": 31},
    {"Name": "John", "Age": 24},
    {"Name": "Bob", "Age": 22}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e770ba6bbc41e36cc3cae89"),
        ObjectId("5e770bacbbc41e36cc3cae8a"),
        ObjectId("5e770bb3bbc41e36cc3cae8b"),
        ObjectId("5e770bb8bbc41e36cc3cae8c")
    ]
}

Display all documents from the collection ?

db.demo431.find();
{"_id": ObjectId("5e770ba6bbc41e36cc3cae89"), "Name": "Chris", "Age": 32}
{"_id": ObjectId("5e770bacbbc41e36cc3cae8a"), "Name": "David", "Age": 31}
{"_id": ObjectId("5e770bb3bbc41e36cc3cae8b"), "Name": "John", "Age": 24}
{"_id": ObjectId("5e770bb8bbc41e36cc3cae8c"), "Name": "Bob", "Age": 22}

Example: Replace Complete Document

Replace John's document with completely new data ?

db.demo431.replaceOne(
    {"Name": "John"},
    {"Name": "Robert", "Age": 45}
);
{"acknowledged": true, "matchedCount": 1, "modifiedCount": 1}

Verify Result

db.demo431.find();
{"_id": ObjectId("5e770ba6bbc41e36cc3cae89"), "Name": "Chris", "Age": 32}
{"_id": ObjectId("5e770bacbbc41e36cc3cae8a"), "Name": "David", "Age": 31}
{"_id": ObjectId("5e770bb3bbc41e36cc3cae8b"), "Name": "Robert", "Age": 45}
{"_id": ObjectId("5e770bb8bbc41e36cc3cae8c"), "Name": "Bob", "Age": 22}

Key Points

  • replaceOne() replaces the entire document content except the _id field
  • It's faster than updateOne() with $set for complete document replacement
  • The _id field remains unchanged automatically

Conclusion

Use replaceOne() for the fastest way to update entire documents in MongoDB. It efficiently replaces all fields while preserving the document's unique identifier.

Updated on: 2026-03-15T02:57:48+05:30

609 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements