skip to Main Content

Here is what 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.

What can I try to solve this?

2

Answers


  1. 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

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search