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.
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.
© 2022 - 2025 — McMap. All rights reserved.