Home > OS >  how to replace only one object from array in mongoDB
how to replace only one object from array in mongoDB

Time:09-10

i have following bson data in mongoDB

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

i want to replace object where partyName is "p2" with new object. i tried this

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

it replace the object "p2" but it delete the other objects ( p1 and p3 ).i want to keep p1,p3 and updated p2 objects. please help me to overcome this problem

CodePudding user response:

Work with $ positional operator.

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

Demo @ Mongo Playground

  • Related