Search code examples
mongodbmongodb-queryinsert-updatemongodb-update

Difference between the UpdateOne() and findOneAndUpdate Methods in Mongo DB


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.


Solution

  • Insert a document in an otherwise empty collection using the mongo-shell to start:

    db.users.insertOne({name: "Jack", age: 11})
    

    UpdateOne

    db.users.updateOne({name: "Jack"}, {$set: {name: "Joe"}})
    

    This operation returns an UpdateResult.

    { acknowledged: true,
      insertedId: null,
      matchedCount: 1,
      modifiedCount: 1,
      upsertedCount: 0 }
    

    FindOneAndUpdate

    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.