How do you update a MongoDB document while replacing the entire document?

To update a MongoDB document while replacing the entire document, use the update() or replaceOne() method without update operators like $set. This replaces all fields except the _id field.

Syntax

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

// Or use replaceOne() (recommended)
db.collection.replaceOne(
    { filter },
    { newDocument }
);

Sample Data

Let us first create a collection with a document:

db.replacingEntireDocumentDemo.insertOne({
    "StudentFirstName": "John",
    "StudentLastName": "Smith", 
    "StudentCountryName": "US"
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5cd3119bb64f4b851c3a13e8")
}

Display the document from the collection:

db.replacingEntireDocumentDemo.find().pretty();
{
    "_id": ObjectId("5cd3119bb64f4b851c3a13e8"),
    "StudentFirstName": "John",
    "StudentLastName": "Smith",
    "StudentCountryName": "US"
}

Example: Replace Entire Document

Replace the entire document with new values:

db.replacingEntireDocumentDemo.update(
    {
        "StudentFirstName": "John",
        "StudentLastName": "Smith",
        "StudentCountryName": "US"
    },
    {
        "StudentFirstName": "David",
        "StudentLastName": "Miller",
        "StudentCountryName": "AUS"
    }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Verify Result

Display all records to confirm the replacement:

db.replacingEntireDocumentDemo.find().pretty();
{
    "_id": ObjectId("5cd3119bb64f4b851c3a13e8"),
    "StudentFirstName": "David",
    "StudentLastName": "Miller",
    "StudentCountryName": "AUS"
}

Key Points

  • The _id field is preserved during document replacement.
  • All other fields are completely replaced with the new document structure.
  • Use replaceOne() for better clarity in modern MongoDB versions.

Conclusion

Document replacement in MongoDB overwrites all fields except _id with the new document structure. This is useful when you need to completely restructure a document while maintaining its identity.

Updated on: 2026-03-15T01:06:46+05:30

181 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements