2016-08-05 43 views
0

我使用express和mongodb npm模块将数据插入到具有超过1300个收集项目的集合中。我从一个也有1300多个对象的json文件中提取数据。使用下面的代码,一切都会被正确插入,直到我在mongodb集合中达到100个项目。有没有办法解决这个问题,而不会把事情分解成多个集合?如何在mongodb中迭代超过100个项目

我使用的节点下面的代码:

MongoClient.connect(url, function(err, db) { 
    db.collection('players').find().forEach(function(myDoc) { 
    for(var i = 0; i < jsonfile.length; i++) { 
     if (myDoc.player_ID == jsonfile[i].playerID && myDoc.stint_ID == 1) { 
     db.collection('players').updateOne(
      { 'player_ID' : jsonfile[i].playerID}, 
      { $set: { 
      'strikeOut' : jsonfile[i].SO } 
      }, function(err, result) { 
      console.log(err); 
      db.close(); 
      } 
     ); 
     } else { 
     return; 
     } 
    } 
    }); 
}); 

回答

1

最好用这里的bulkWrite API,它极大地提高了性能,因为写操作是成批只有一次发送到服务器。由于该方法不会向服务器发送每个写请求(与当前更新语句中的forEach()循环一样),但每1000次请求只发送一次,因此使得更新效率和速度比目前更高:

var MongoClient = require('mongodb').MongoClient, 
    bulkUpdateOps = []; 

MongoClient.connect(url, function(err, db) { 
    // Get the collection 
    var col = db.collection('players'); 
    col.find().forEach(function(myDoc) { 
     for(var i = 0; i < jsonfile.length; i++) { 
      if (myDoc.player_ID == jsonfile[i].playerID && myDoc.stint_ID == 1) { 
       bulkUpdateOps.push({ 
        "updateOne": { 
         "filter": { "player_ID": jsonfile[i].playerID }, 
         "update": { "$set": { "strikeOut" : jsonfile[i].SO } } 
        } 
       });  
       if (bulkUpdateOps.length === 1000) { 
        col.bulkWrite(bulkUpdateOps).then(function(r) { 
         // do something with the result 
         console.log(r); 
        }); 
        bulkUpdateOps = []; 
       } 
      } 
     } 
    });   

    if (bulkUpdateOps.length > 0) { 
     col.bulkWrite(bulkUpdateOps).then(function(r) { 
      console.log(r); 
      db.close(); 
     }); 
    } 
}