I set up a sharded database and enable sharding on the collection(EmailAddress as shardKey). And below is my code to insert in the collection (Insert only if EmailAddress doesn't exist already)
var con = MongoDBConnection.Connection;
var database = con.GetDatabase("MyDbName");
var collection = database.GetCollection<MyDbClass>("MyCollectionName");
var testFilter = new BsonDocument("EmailAddress", "abc@gmail.com");
var result = collection.UpdateOne(testFilter, Builders<MyDbClass>.Update
.SetOnInsert("Name", "John Doe")
.SetOnInsert("EmailAddress", "abc@gmail.com")
.SetOnInsert("City", "NY"), new UpdateOptions() { IsUpsert = true });
When I run this code, It gives me this error "A bulk write operation resulted in one or more errors. Failed to target upsert by query :: could not extract exact shard key"
Any help would be greatly appreciated !