Vol*_*lox 11 javascript bulkinsert mongodb node.js npm
如何执行批量插入并在重复键错误的情况下继续?
我有一个集合,在id
字段上有一个唯一的索引(不是 _id
),里面有一些数据.然后我获得更多数据,我想只将非现有文档添加到集合中.
我有以下代码:
let opts = {
continueOnError: true, // Neither
ContinueOnError: true, // of
keepGoing: true, // this
KeepGoing: true, // works
};
let bulk = collection.initializeUnorderedBulkOp( opts );
bulk.insert( d1 );
bulk.insert( d2 );
bulk.insert( d3 );
...
bulk.insert( dN );
let result = yield bulk.execute( opts ); // this keep throwing duplicate key error
Run Code Online (Sandbox Code Playgroud)
我只是想忽略错误,让批量完成所有排队的操作.
我搜索了npm模块api和MongoDB api中的Bulk,initializeUnorderedBulkOp和Bulk写的文档没有运气.
同样在无序操作的文档中,他们说:
错误处理
如果在处理其中一个写操作期间发生错误,MongoDB将继续处理列表中的剩余写操作.
这不是真的(至少在我的情况下):(
欢迎任何想法!
您可以使用db.collection.insertMany(),(版本3.2中的新增功能):
下令:假
如果命令为false,并且在重复键错误的情况下,插入操作将继续任何剩余的文档.
以下是文档链接:https: //docs.mongodb.com/v3.2/reference/method/db.collection.insertMany/
小智 5
db.hobbies.insertMany([{_id: "yoga", name: "Yoga"}, {_id: "cooking", name: "Cooking"}, {_id: "hiking", name: "Hiking"}], {ordered: true})
Run Code Online (Sandbox Code Playgroud)
{ordered: true} 是插入语句的默认行为
如果您希望 mongodb 在一个或多个因任何原因失败后继续尝试插入其他文档,您必须将ordered 设置为false。请参阅下面的示例:
db.hobbies.insertMany([{_id: "yoga", name: "Yoga"}, {_id: "cooking", name: "Cooking"}, {_id: "hiking", name: "Hiking"}], {ordered: false})
Run Code Online (Sandbox Code Playgroud)