Search code examples
databasemongodbmongoosenosqlmongodb-update

MongoDB - How to replace only one object from array


I have the following BSON data in MongoDB:

[
  {
     partyName : "p1",
     poNumber : "789",
  },
  {
     partyName : "p2",
     poNumber : "700",
  },
  {
     partyName : "p3",
     poNumber : "889",
  }
]

I want to replace the object where partyName is "p2" with a new object. I tried this

const user1 = await User.findOneAndUpdate({"array.partyName" :"p2"},{$set:{array:newObject}})

It replaces the object "p2" but it deletes the other objects (p1 and p3). I want to keep p1, and p3, but only update the p2 objects.

How can I overcome this problem?


Solution

  • Work with the $ positional operator.

    await User.findOneAndUpdate(
      { "array.partyName" :"p2" },
      { $set: { "array.$": newObject } }
    )
    

    Demo @ Mongo Playground