Search code examples
c#mongodbmongodb-.net-driver

MongoDb C# concurrency issues with upsert


I have a quite simple method for upserting an entry in a collection:

    public void UpsertEntry(string collectionName, Entry entry)
    {
        var collection = GetCollection(collectionName);
        var filter = Builders<Entry>.Filter.Eq(x => x.Key, entry.Key);
        var update = Builders<Entry>.Update
            .SetOnInsert(x => x.Id, ObjectId.GenerateNewId())
            .SetOnInsert(x => x.Key, entry.Key)
            .Set(x => x.LastUpdated, DateTime.Now)
            .Set(x => x.Data, entry.Data)
            .Inc(x => x.Version, 1);

        var result = collection.UpdateOne(filter, update, new UpdateOptions
        {
            IsUpsert = true
        });
    }

The collection has a unique index on Key.

I'm calling the UpsertEntry method in a Parallel.For loop

        Parallel.For(0, 100, i =>
        {
            entry.Key = $"key+{i}";
            UpsertEntry(coll, entry);
        });

I'd expect to get 100 record inserted, but instead I receive a E11000 duplicate key error collection: TestDB.test::c7 index: key_1 dup key: { : "key+1" }. Why am I experiencing concurrency issues? What's wrong with my code?


Solution

  • I resolved it and it has nothing to do with the driver itself. I didn't noticed I was re-using the same instance of the class Entry :-)