Home > Back-end >  How to upsert documents with dynamic update values in mongodb?
How to upsert documents with dynamic update values in mongodb?

Time:07-29

I am looking for a query that varies the update value according to the document.

Such as, given schema is Carts

finding many documents with array, suppose

user: { $in: [userid_1,userid_2,userid_3]}

And some common field to upsert - items: ['item']

Upserted documents should result like following; if not found user, it will create

{user:userid_1,items: ['item']}
{user:userid_2,items: ['item']}
{user:userid_3,items: ['item']}

On some research, found the Bulk operator, but I am unable to make use of it.

Notes:

'for loops' would make it easier, but it will be slower, thus just requiring the query.

CodePudding user response:

One option is to use a bulk operation for this:

const cartsBulk = cartsModel.collection.initializeUnorderedBulkOp();
for (const userid of [userid_1,userid_2,userid_3]) {
  cartsBulk.find({user: {$in: [userid_1,userid_2,userid_3]}).upsert().update({$set:{items: ["item"]}});
}
await cartsBulk.execute()
  • Related