在 mongo shell 中,您可以使用该bulkWrite()
方法快速高效地进行更新。考虑以下示例:
var entitiesCol = db.getCollection('entities'),
counter = 0,
ops = [];
entitiesCol.find({
"type": "item",
"prices.0": { "$exists": false }
}).snapshot().forEach(function(item){
ops.push({
"updateOne": {
"filter": { "_id": item._id },
"update": {
"$push": {
"prices": { "value": item.price }
}
}
}
});
counter++;
if (counter % 500 === 0) {
entitiesCol.bulkWrite(ops);
ops = [];
}
})
if (counter % 500 !== 0)
entitiesCol.bulkWrite(ops);
counter
如果您的集合很大,上面的变量可以有效地管理您的批量更新。它允许您批量更新操作并以 500 个批次将写入发送到服务器,这可以为您提供更好的性能,因为您不会将每个请求都发送到服务器,而是每 500 个请求发送一次。
对于批量操作,MongoDB 规定了每批1000 次操作的默认内部限制,因此从某种意义上说,选择 500 个文档是好的,因为您可以对批量大小进行一些控制,而不是让 MongoDB 强加默认值,即对于规模较大的操作> 1000 个文档。