There is a problem when updating multiple documents using an array of identifiers using $ in

This query does the job perfectly:

db.collection.update( { "_id": oneIdProvided }, { $inc: { "field": 5 } },{ upsert: true } ) 

Now, I would like to do the same operation several times with different identifiers, I thought that a good way was to use $ in, and so I tried:

 db.collection.update( { "_id": { $in: oneArrayOfIds} }, { $inc: { "field": 5 } },{ upsert: true } ) 

The problem is this: if one of the provided identifiers in the array does not exist in the collection, a new document is created (this is what I want), but an automatic identifier will be assigned without using the identifier that I provided and was looking for.

One solution that I see is to first make a paste request with my array of identifiers (existing ones will not be changed), and then fulfill my update request with upsert: false

Do you see a way to do this in just one request?

+5
source share
1 answer

We can do this by performing several write operations using the bulkWrite() method.

 function* range(start, end, step) { for (let val=start; val<end; val+=step) yield val } let oneArrayOfIds; // For example [1, 2, 3, 4] let bulkOp = oneArrayOfIds.map( id => { return { "updateOne": { "filter": { "_id": id }, "update": { "$set": { "field": 5 } }, "upsert": true } }; }); const limit = 1000; const len = bulkOp.length; let chunks = []; if (len > 1000) { for (let index of range(0, len, limit)) { db.collection.bulkWrite(bulkOp.slice(index, index+limit)); } } else { db.collection.bulkWrite(bulkOp); } 
+2
source

Source: https://habr.com/ru/post/1262586/


All Articles