2
有没有什么办法让我可以使用updateMany方法中的当前索引或文档编号或光标ID?node.js mongodb update索引有很多
例如:
db.collection("users").updateMany({}, { $set: {"uname": "user_" + $index}});
这里,$索引意味着文档的当前号或索引或串行。
有没有什么办法让我可以使用updateMany方法中的当前索引或文档编号或光标ID?node.js mongodb update索引有很多
例如:
db.collection("users").updateMany({}, { $set: {"uname": "user_" + $index}});
这里,$索引意味着文档的当前号或索引或串行。
没有办法与updateMany方法来执行这种操作。然而,有效的解决方案是将find和bulkWrite组合使用。
实施例(使用函数发生器和产率):
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});