What is the difference between the UpdateOne()
and the findOneAndUpdate()
methods in Mongo DB?
I can't seem o understand their differences. Would appreciate it if a demonstrative example using UpdateOne()
and findOneAndUpdate
could be used.
Insert a document in an otherwise empty collection using the mongo-shell
to start:
db.users.insertOne({name: "Jack", age: 11})
db.users.updateOne({name: "Jack"}, {$set: {name: "Joe"}})
This operation returns an UpdateResult
.
{ acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0 }
db.users.findOneAndUpdate({name: "Joe"}, {$set: {name: "Jill"}})
This operation returns the document that was updated.
{ _id: ObjectId("62ecf94510fc668e92f3cecf"),
name: 'Joe',
age: 11 }
FindOneAndUpdate
is preferred when you have to update a document and fetch it at the same time.