UpdateMany document with array of objects in mongodb

Viewed 196

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?

1 Answers

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

Related