2

I have a mongodb collection which looks like this

[
    {
        pId: "p1",
        apikey: "a2",
        count: 0
    },
    {
        pId: "p2",
        apikey: "a2",
        count: 0
    },
    {
        pId: "p2",
        apikey: "a3",
        count: 0
    }
]

I have an input which is array of object. I want to increment the counts. The input objects are like below

[
    {
        pId: "p1",
        apikey: "a2"
    },
    {
        pId: "p2",
        apikey: "a2"
    }
]

this above 2 input objects matches with the first 2 objects present in the collection. i was incrementing by iterating the input array. Is there any other way to achieve this?

2
  • 1) which field you want to match pId or apiKey or both? 2) what if an element no found?
    – turivishal
    Commented Jun 2, 2021 at 14:14
  • on both, if not found no change should happen. Commented Jun 3, 2021 at 1:47

1 Answer 1

0

You can pass your input items in $or condition and increment count by 1 using $inc,

let items = [
  { pId: "p1", apikey: "a2" },
  { pId: "p2", apikey: "a2" }
];
db.collection.updateMany({ $or: items }, { $inc: { count: 1 } });

Playground

1
  • 1
    This is clean and simple $or works like this only which I forgot, thanks:) Commented Jun 3, 2021 at 11:02

Not the answer you're looking for? Browse other questions tagged or ask your own question.