Dublicate documents with transactions upsert

Hello. i use latest mongodb 5. Found intresting moment then update in parallel is not exists document with UPSERT by transaction i got dublicate documents

 using var session = DB.Client.StartSession();
 session.StartTransaction();

userId = 1;

        try
        {
          var u = Builders<Balance>.Update.Inc(f => f.Quantity, 5)
            .SetOnInsert(f => f.Id, Guid.NewGuid())

        var balanceAfter = Balances.FindOneAndUpdate<Balance>(session, c => c.UserId == 
         userId, u, new FindOneAndUpdateOptions<Balance>
        {
            IsUpsert = true,
            ReturnDocument = ReturnDocument.After
        });
            session.CommitTransaction();
        }
        catch (Exception e)
        {
            Console.WriteLine("Error MongoDB Transaction: " + e.Message);
            session.AbortTransaction();
        }

But if i run second time then DOCUMENT exists , all work current.

How to make the first option work like the second one?

I think the problem is that transactions with an upset do not understand that they will update the same document

There is no way for the system to know you didn’t intend to create a duplicate unless you have a unique index on appropriate field(s). This is not related to transactions and it’s described in the documentation for update and findAndModify.

Asya

2 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.