Reputation: 10882
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.
Upvotes: 1
Views: 611
Reputation: 2743
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
Upvotes: 2