Update Data

To Update Data in MongoDB document or collections, we use updateOne, updateMany and replaceOne methods.

We will use a sample database (cars ) shown below for reference. The name of collection is suzuki.

Sample Database


[{"name": "swift","type": "hatchback","price":"800000"},
 {"name": "ciaz","type": "sedan","price":"1000000"},
 {"name": "baleno","type": "hatchback","price":"850000"},
 {"name": "scross","type": "crossover","price":"11500000"},
 {"name": "brezza","type": "suv","price":"990000"},
 {"name": "gypsy","type": "suv","price":"750000"}
]    

updateOne

updateOne method is used to update the first document.

$set is a update operator in MongoDB. It comes under Field Update Operators.

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) 
db.suzuki.update({name:'swift'},{$set:{fuel:'petrol'}})

Check after update

{ "_id" : ObjectId("5eb44282ea2adece905a24b0"), "name" : "swift", "type" : "hatchback", "price" : 800000, "fuel" : "petrol" }
db.suzuki.find({name:'swift'}})

updateMany

updateMany is used to update more than one documents.

$set update operator is again required in below example.

{ "acknowledged" : true, "matchedCount" : 4, "modifiedCount" : 4 } 
db.suzuki.updateMany({fuel:'petrol'},{$set:{emission:'bs6'}})

Check after update

{ "_id" : ObjectId("5eb44282ea2adece905a24b0"), "name" : "swift", "type" : "hatchback", "price" : 800000, "fuel" : "petrol", "emission" : "bs6" }
db.suzuki.find({name:'swift'}})

replaceOne

replaceOne method is used to replace a document from collection (except _id).

replaceOne method will replace entire data in document.

{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
db.suzuki.replaceOne({name:'brezza'},{name:'vitara brezza',fuel:'petrol',price:'990000'})

Check after update

{ "_id" : ObjectId("5eb53b3491fc73f290f38254"), "name" : "vitara brezza", "fuel" : "petrol", "price" : "990000" }
db.suzuki.find({name:'vitara brezza'})