Home > Software engineering >  Updating an object property that is inside an array of objects
Updating an object property that is inside an array of objects

Time:04-14

I am trying to update specfic property of an object inside an array of objects.

The collection: I want to update the ticket property inside the first object in the array.

I want to update the ticket property inside the first object in the array. This is what i've come up with:

Flight.findOneAndUpdate({_id: "625764663bddec3da194ebc8"}, {$set: {"ecoSeats.$[0].ticket": "Hello"}});

But nothing seems to be updated.

CodePudding user response:

@Yong Shun 's answer is correct. I think your query is the problem, make sure you use string or ObjectId in _id

_id: "625764663bddec3da194ebc8" != _id: ObjectId("625764663bddec3da194ebc8")

db.collection.update({
  _id: ObjectId("625764663bddec3da194ebc8")
},
{
  $set: {
    "ecoSeats.0.ticket": "Hello"
  }
},
{
  multi: true
})

mongoplayground

  • Related