2017-09-25 64 views
0

我试图将数据插入到mongodb集合中。我在一个循环,在每次迭代中得到下面的示例数据运行,Mongodb如何从javascript批量插入

13:24:24:007,Peter,male,3720,yes 
13:24:24:007,John,female,1520,yes 
13:24:24:023,John,female,9720,yes 
13:24:24:023,Mario,male,9820,no 
13:24:24:023,Katy,male,4320,no 
13:24:24:038,John,male,3620,no 

这些数据是字段名,

currenttime, custname, gender, custid, ismember 

我想与适当的字段名称将数据插入到MongoDB的集合。我不知道如何在我的要求中使用mongodb批量插入。我可以把这个数据放在一个数组变量中(用新行溢出),并将这个数组的每个项目都带到另一个数组(通过逗号分隔),并在循环中创建一个对象,最后插入一个数组,将该对象转换为mongodb集合。但是这种方法看起来非常简单和缓慢。我坚信必须有更好的方式来做到这一点。请建议。

+0

https://docs.mongodb.com/manual/reference/method/db.collection.insertMany/ –

+0

你可能想看看[mongoimport](https://docs.mongodb.com/manual /reference/program/mongoimport/index.html) – chridam

+0

我还没有试过mongoimport。将现在检查它。有一个问题,我们可以使用mongoimport来连续增长的文件吗? – sand

回答

0

如果运行循环之前的结果有点像这样,你可以直接使用插入函数插入数组。

var data= [{currenttime:13:24:24:007, 
     custname:"Peter", 
     gender:"male", 
     custid:"3720", 
     ismember:"yes"}, 
     {currenttime:13:24:24:007, 
     custname:"John", 
     gender:"male", 
     custid:"1520", 
     ismember:"yes"} 
    ] 

    db.collection.insert(data,function(err,data){ 
     if(!err){ 
      //send sucess message 
     }else{ 
     //send a failure message 
     } 
})