MongoDB: How to update many using array of objects, and each object with it's own _id?

Viewed 436

I have an array of objects, where each object have it's own "_id". I am trying to use updateMany(), instead calling updateOne for each object, so I don't make too many requisitions to mongoDB.

for example, this is the object:

[
  {
    _id: 123,
    name: "apple",
    qty: 2
  },
  {
    _id: 555,
    name: "melon",
    qty: 1
  },
  {
    _id: 799,
    name: "avocado",
    qty: 0
  }
]

I want to updateMany() with this array of objects, and each object must be a Document inside a collection, I tried many solutions, and none worked, only worked with insert() where I can send the entire array, and it will make each object be a Document, the problem for using insert is, this object comes every day, and some values may change, like name and qty, but _id keeps the same.

I tried the following

sync function updateMany(client) {
            result = await client.db("sample_db").collection("CollectionA")
                ..updateMany({},
                    {asd},
                    {upsert: true});
        }

but didn't work, I tried other solutions to, like, making each object use $setOnInsert for _id and $set the rest..

Is it possible to do it without the need of insert() or making one call for each object?

The language I am using is Javascript, running on Node.JS.

0 Answers
Related