我不建议将 {multi: true} 用于更大的数据集,因为它的可配置性较低。
使用批量插入的更好方法。
批量操作对调度程序任务非常有帮助。假设您必须每天删除超过 6 个月的数据。使用批量操作。它的速度很快,不会减慢服务器的速度。当您插入、删除或更新超过十亿个文档时,CPU、内存使用情况并不明显。我发现 {multi:true} 在处理数百万多个文档时会降低服务器速度(需要对此进行更多研究。)
请参阅下面的示例。它是一个 js shell 脚本,也可以作为节点程序在服务器中运行。(使用 npm 模块 shelljs 或类似的方式来实现)
将 mongo 更新到 3.2+
更新多个唯一文档的正常方式是
let counter = 0;
db.myCol.find({}).sort({$natural:1}).limit(1000000).forEach(function(document){
counter++;
document.test_value = "just testing" + counter
db.myCol.save(document)
});
我尝试了 310-315 秒。更新一百万个文档需要 5 分钟以上。
我的收藏包含超过 1 亿个文档,因此其他人的速度可能会有所不同。
同样使用bulk insert是
let counter = 0;
// magic no.- depends on your hardware and document size. - my document size is around 1.5kb-2kb
// performance reduces when this limit is not in 1500-2500 range.
// try different range and find fastest bulk limit for your document size or take an average.
let limitNo = 2222;
let bulk = db.myCol.initializeUnorderedBulkOp();
let noOfDocsToProcess = 1000000;
db.myCol.find({}).sort({$natural:1}).limit(noOfDocsToProcess).forEach(function(document){
counter++;
noOfDocsToProcess --;
limitNo--;
bulk.find({_id:document._id}).update({$set:{test_value : "just testing .. " + counter}});
if(limitNo === 0 || noOfDocsToProcess === 0){
bulk.execute();
bulk = db.myCol.initializeUnorderedBulkOp();
limitNo = 2222;
}
});
最佳时间是 8972 毫秒。因此,平均而言,更新一百万个文档只需要 10 秒。比旧方法快 30 倍。
将代码放入 .js 文件并作为 mongo shell 脚本执行。
如果有人找到更好的方法,请更新。让我们以更快的方式使用 mongo。