When I insert multiple documents with insert(docs...), Operation is failing & fails to insert documents if one duplicate key in a document exists in list of documents. How can I ignore this error, So all documents but not the duplicates can be inserted successfully.
1 Answers
By default when you insert documents using MongoDB's .insertMany()
or similar then it would be ordered insert { ordered: true }
where if there is an error while inserting a document in an array of documents then the entire operation will fail by not inserting that particular document and rest others after that one. So to make this process unordered you need to pass an option to .insertMany()
which is { ordered: false }
.
Ref : MongoDB-insertMany-Unordered-inserts
So when it comes to mgo driver, You may need to use func (b *Bulk) Unordered()
.
Ref : mgo-Unordered
Note : Your best option would be is to check why duplicate key error occurred & which key is causing this issue if you've multiple unique key constraints on DB & make a correction to documents or unique indexes on fields, rather than skipping docs from inserts.

- 17,086
- 6
- 32
- 46
-
1Thanks for your answer, mgo has no insertMany interface or param "unordered", but bluk.Unordered() can solve my problem. – zxxhonest Mar 02 '20 at 06:37
-
@zxxhonest : yes it might not have it cause it’s a driver for a programming language it can have it or alternatively drivers do provide wrapper functions for native ones but insertMany is a mongo shell function which I’ve mentioned for reference :-) – whoami - fakeFaceTrueSoul Mar 02 '20 at 06:51