Ranjeet Eppakayala
Ranjeet Eppakayala

Reputation: 3028

How to upsert documents with dynamic update values in mongodb?

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.

Upvotes: 1

Views: 80

Answers (1)

nimrod serok
nimrod serok

Reputation: 16033

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()

Upvotes: 1

Related Questions