Thursday, March 18, 2021

update() vs updateMany()

To avoid accidents replace all fields in many documents, I would suggest do not use update(). Use below shell methods instead:

replaceOne() : replace 1 document.

updateOne() : update 1 document on specific fields.

updateMany(): update many document on specific fields.


Good Example:

db.flight.updateOne({depart:"KLIA"}, {$set:{arrivaltime:"3pm"}})

db.flight.updateMany({depart:"KLIA"}, {$set:{arrivaltime:"3pm"}})

db.flight.replaceOne({depart:"KLIA"}, {arrivaltime:"3pm"})


Bad Example:

db.flight.update({depart:"KLIA"}, {arrivaltime:"3pm"})

No comments:

Post a Comment