Nafis Abdullah Khan
Nafis Abdullah Khan

Reputation: 2400

Node.js mongodb updateMany with index

Is there any way so that I can use the current index or document number or cursor id in updateMany method?

For example:

db.collection("users").updateMany({}, { $set: {"uname": "user_" + $index}});

Here the $index means the current number or index or serial of the document.

I am using MongoDB Node.JS Driver 2.2

Upvotes: 3

Views: 3384

Answers (1)

Nafis Abdullah Khan
Nafis Abdullah Khan

Reputation: 2400

There is no way with updateMany method to perform this kind of operations. However an efficient solution is to use find and bulkWrite in combination.

Example (using function generators and yield):

var coll = db.collection("users");
var Users = yield coll.find().toArray();
var bulkArray = [];
Users.forEach(function* (d, i) {
    bulkArray.push({ updateOne: { filter: { _id: mongodb.ObjectID(d._id) }, 
        update: { $set: { uname: 'user_' + i }}, upsert:true });
});
yield coll.bulkWrite(bulkArray, {ordered:true, w:1});

Upvotes: 2

Related Questions