0

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?

0

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

7 Comments

I am really thankful to you. thank you very much bro. Keep doing the great work.
I have another question if you could answer. Imagine in this collection only reportTypes is an empty array and i have to insert this document ({ reasonId: ObjectId(2353...), count: 0 }) only if it doesn't exist in the reportTypes array, otherwise do nothing. So my quest is how can i find weather reportTypes contains an object with some reasonId and how to update reportTypes array based on this condition.
maybe something like this using $push: mongoplayground.net/p/0X0o8r57wIA
alternatively you can use update/agg.pipeline: mongoplayground.net/p/MXystkuhFzT
There is free of charge trainings provided officially by mongodb they are the best to start with ...
|
0

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

3 Comments

Yeah bro i have tried this sol. but it gives me { acknowledged: false } and its not updating in my collection. Also i want to increment count by 1 (based on it's previous value).
Okay so I updated the code snippet, try that instead
Thanks brother for giving your precious time. But it isn't working it is giving me this error. But yeah my problem is solved with arrayfilter. Thank again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.