How can I ignore duplicate key error & proceed insertion, While insert many documents with MongoDB-mgo?
Asked Answered
P

1

8

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.

Pournaras answered 2/3, 2020 at 3:38 Comment(0)
C
13

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.

Colonize answered 2/3, 2020 at 4:4 Comment(2)
Thanks for your answer, mgo has no insertMany interface or param "unordered", but bluk.Unordered() can solve my problem.Pournaras
@Pournaras : 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 :-)Colonize

© 2022 - 2025 — McMap. All rights reserved.