Home > Enterprise >  How to update a property of object in a nested array in MongoDB?
How to update a property of object in a nested array in MongoDB?

Time:08-28

I am trying to update a property from nested array object. I use this code but not working. This is my data

[
  {
    _id: ObjectId("630a869a887d39ef359ef6e6"),
    firstName: 'Esra',
    lastname: 'Demirci',
    age: 33
  },
  {
    _id: ObjectId("630a86a5887d39ef359ef6e7"),
    firstName: 'Efe',
    lastname: 'Demirci',
    age: 7,
    history: [ { disease: 'flue', threatment: 'given serum' } ]
  },
  {
    _id: ObjectId("630a8e10887d39ef359ef6e8"),
    firstName: 'Ali',
    lastname: 'Demirci',
    age: 34,
    history: [
      { disease: 'cold', threatment: 'medicine given' },
      { disease: 'alergy', threatment: 'refered alergy department' }
    ]
  }
]

This is my query in mongodb

 db.patientData.update({"history.disease":"cold"},{$set:{"history.disease":"ali updated this one"}})

I wanna update data which has disease:"cold" value to new value.

CodePudding user response:

Try using the $ sign when updating in MongoDB, like so:

db.patientData.update({"history.disease":"cold"},{$set:{"history.$.disease":"ali updated this one"}})
  • Related