代码之家  ›  专栏  ›  技术社区  ›  Anna

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

  •  1
  • Anna  · 技术社区  · 6 年前

    我有这个剧本:

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

    问题是它需要很长时间才能执行。 你知道怎么加快速度吗? 谢谢!

    2 回复  |  直到 6 年前
        1
  •  1
  •   chridam Gino Claudi    6 年前

    使用 bulkWrite API通过批量发送insert操作来优化插入操作,甚至更好的是,它为您提供了关于成功和失败的真正反馈。

    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: 使用 Bulk 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(); }
    
        2
  •  0
  •   Mạnh Quyết Nguyễn    6 年前

    尝试聚合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
    ])