Home > Mobile >  update a value inside array of objects, inside a document in mongodb
update a value inside array of objects, inside a document in mongodb

Time:03-31

here is my collection looks like

enter image description here

Now suppose i have to update count of 2nd document whose reportTypes.reasonId is 300. I have access to _id as well as reasonId to update the count. I am using mongoose to query things in my node application.

Please help me with this, I am stuck with this problem for days now and i have tried many solution but nothing is working.

CodePudding user response:

You can do it via arrayFilters:

db.collection.update(
   { 
    managerId:3 
   },
   {
    $inc:{"reportTypes.$[x].count":1} 
   },
   { 
   arrayFilters:[{"x.reasonId":300  }]
   }
  )

playground

Explained: Specify the matching document in the query part and create arrayFilter "x" matching the correct reportTYpes array subdocument , in the update part use the $inc operation to increment the count value in the example with 1

CodePudding user response:

you should use dot notation and the $ update operator to do this: (I'm assuming your collection is called Reason)

var conditions = {
  '_id': '6244........',
  'reasonTypes.reasonId': 300
}
var update = {
  $inc: {
    'reasonTypes.$.count': 1
  }
};

Reason.update(conditions, update, function(err) {
  // Handle error here
})

You can find more on the operator here mongo $ update operator

  • Related