Hi, @AnRy,

Welcome to the MongoDB Community Forums. I understand that you’re encountering a MongoDuplicateKeyException when performing simultaneous upserts.

In MongoDB the _id field is required and must be unique. If one is not specified the driver (or server) will automatically generate an _id for you using an ObjectId by default. You are encountering a MongoDuplicateKeyException because your application is trying to insert two documents with the same _id (which is mapped to Id in C#).

The reason for the duplicate inserts is due to performing upserts. When performing an upsert, an update is performed if the filter matches one or more documents and an insert if the filter does not match any documents. Note that whether an insert or an update is performed depends on matching of the filter criteria, not on whether the _id exists.

I would suggest changing your application logic to only match on _id. You will have to determine how to implement your additional filter criteria separately from the upsert filter. Hope that helps!

Sincerely,
James