1
votes

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

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.

1
When I last tried it, it wasn't possible.Sergio Tulentsev
I believe you'll need to insert each document individually right now.WiredPrairie

1 Answers

2
votes

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/).

For Node.js, it would be something like

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

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