考虑以下场景,两个集合名称为title
和attribute
。
title
集合包含以下文件:
[{
_id: 12345,
title: "title"
},
{
_id: 12346,
title: "title1"
}]
并且attribute
集合包含以下文档:
[{
_id: 12345,
newAttribute: "newAttribute12345"
},
{
_id: 12346,
newAttribute: "newAttribute12346"
},
{
_id: 12347,
newAttribute: "newAttribute12347"
}]
并且您想更新title
集合,因为使用此标准title._id = attribute._id
使用带有以下脚本的mongo 批量更新:
var bulk = db.title.initializeOrderedBulkOp();
var counter = 0;
db.attribute.find().forEach(function(data) {
var updoc = {
"$set": {}
};
var updateKey = "newAttribute";
updoc["$set"][updateKey] = data.newAttribute;
bulk.find({
"_id": data._id
}).update(updoc);
counter++;
// Drain and re-initialize every 1000 update statements
if(counter % 1000 == 0) {
bulk.execute();
bulk = db.title.initializeOrderedBulkOp();
}
})
// Add the rest in the queue
if(counter % 1000 != 0) bulk.execute();