需要唯一索引时将多个文档插入MongoDB

时间:2022-08-08 04:20:15

My collection P has a unique index on the phone field:

我的收藏P在电话领域有一个独特的索引:

db.P.ensureIndex( { phone: 1 }, { unique: true, dropDups: true } )
db.P.insert( {phone:"555-1234"} )

If I insert an array of documents, where even one document has a duplicate key:

如果我插入一个文档数组,即使一个文档有一个重复的键:

db.P.insert( [{phone:"911"},{phone:"555-1234"}] )
> E11000 duplicate key error index: test.P.$phone_1  dup key: { : "555-1234" }

The entire insert fails, and the valid number is not inserted.

整个插入失败,并且未插入有效数字。

Question: How can I do bulk inserts, make sure the valid documents are inserted, and get information on which inserts failed? Bonus points for showing code with the nodejs api.

问题:如何进行批量插入,确保插入有效文档,并获取有关哪些插入失败的信息?使用nodejs api显示代码的加分点。

1 个解决方案

#1


2  

MongoDB drivers have a "ContinueOnError" option that would cause mongo to skip records with duplicate unique keys. As far as identifying what was skipped, per documentation: "If multiple errors occur during a bulk insert, clients only receive the last error generated. (http://docs.mongodb.org/manual/core/bulk-inserts/).

MongoDB驱动程序有一个“ContinueOnError”选项,会导致mongo跳过具有重复唯一键的记录。至于识别跳过的内容,每个文档:“如果批量插入期间发生多个错误,客户端只会收到生成的最后一个错误。(http://docs.mongodb.org/manual/core/bulk-inserts/)。

For Node.js, it would be something like

对于Node.js来说,就像是

db.P.insert( [{phone:"911"},{phone:"555-1234"}], {continueOnError:true} )

http://mongodb.github.io/node-mongodb-native/api-generated/collection.html#insert

#1


2  

MongoDB drivers have a "ContinueOnError" option that would cause mongo to skip records with duplicate unique keys. As far as identifying what was skipped, per documentation: "If multiple errors occur during a bulk insert, clients only receive the last error generated. (http://docs.mongodb.org/manual/core/bulk-inserts/).

MongoDB驱动程序有一个“ContinueOnError”选项,会导致mongo跳过具有重复唯一键的记录。至于识别跳过的内容,每个文档:“如果批量插入期间发生多个错误,客户端只会收到生成的最后一个错误。(http://docs.mongodb.org/manual/core/bulk-inserts/)。

For Node.js, it would be something like

对于Node.js来说,就像是

db.P.insert( [{phone:"911"},{phone:"555-1234"}], {continueOnError:true} )

http://mongodb.github.io/node-mongodb-native/api-generated/collection.html#insert