2016-08-05 22 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(); 
     }); 
    } 
} 
相關問題