Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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
_idfield 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.
Advertisements
