skip to Main Content

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.

2

Answers


  1. 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.

    Login or Signup to reply.
  2. If you need to return the New Document instead of the original document, you can use one of these ways:

    db.users.findOneAndUpdate(
      {name: "Joe"},
      {$set: {name: "Jill"}},
      {returnDocument: "after"}
    )
    

    returnDocument: "before" –> returns the original document (default).
    returnDocument: "after" –> returns the updated document.

    Or

    db.users.findOneAndUpdate(
      {name: "Joe"},
      {$set: {name: "Jill"}},
      {returnNewDocument: true}
    )
    

    returnNewDocument: false –> returns the original document (default).
    returnNewDocument: true –> returns the updated document.

    Note: If both options are set (returnDocument and returnNewDocument), returnDocument takes precedence.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search