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

MongoDBDatabaseBig Data Analytics

Let us first create a collection with a document −

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

Following is the query to display document from a collection with the help of find() method −

> db.replacingEntireDocumentDemo.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5cd3119bb64f4b851c3a13e8"),
   "StudentFirstName" : "John",
   "StudentLastName" : "Smith",
   "StudentCountryName" : "US"
}

Following is the query to update a MongoDB document while replacing the entire document −

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

Let us display all the records from the collection once again −

> db.replacingEntireDocumentDemo.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5cd3119bb64f4b851c3a13e8"),
   "StudentFirstName" : "David",
   "StudentLastName" : "Miller",
   "StudentCountryName" : "AUS"
}
raja
Published on 22-May-2019 15:46:10
Advertisements