从另一个集合更新集合花费的时间太长



我有这个脚本:

db.getCollection('A').find({}).forEach(function(obj){
db.aaa.insert({ "id": obj._id.valueOf() });
});

问题是它需要很长时间才能执行。你知道如何让它更快吗?谢谢

使用bulkWriteAPI可以避免插入性能变慢,该API通过批量发送来优化插入操作,甚至更好的是,它可以为您提供关于成功和失败的真实反馈。

MongoDB 3.2及更高版本:

var ops = [];
db.getCollection('A').find({}).forEach(function(doc) {
ops.push({
"insertOne": {
"document": { "id": doc._id.valueOf() }
}
});
if (ops.length === 500 ) {
db.getCollection('aaa').bulkWrite(ops);
ops = [];
}
});
if (ops.length > 0)  
db.getCollection('aaa').bulkWrite(ops);

MongoDB版本>=2.6和<3.2:使用批量API

var bulk = db.getCollection('aaa').initializeUnorderedBulkOp(),
counter = 0;
db.getCollection('A').forEach(function (doc) {    
bulk.insert({ "id": doc._id.valueOf() });
counter++;
if (counter % 500 === 0) {
// Execute per 500 operations
bulk.execute(); 
// re-initialize every 500 update statements
bulk = db.getCollection('aaa').initializeUnorderedBulkOp();
}
})
// Clean up remaining queue
if (counter % 500 !== 0) { bulk.execute(); }

尝试聚合API:

db.getCollection('A').aggregate([
{$match: {}},
{$project: {
id: {
$toString: "$_id" // Added in mongo 4.0
}
}},
{$out: 'aaa'} // This will override existing collections, use it wisely
])

最新更新