Search code examples
c#mongodbmongodb-.net-driver

Find POCO with MongoDB .Net driver


MongoDB was harder than I remembered! I've tried various versions of if-exists-replace-else-insert with various functions and options. It should be easy, shouldn't it?

It's my personal opinion that the following should work.

var collection = storageClient.GetCollection<Observer>("observers");
await collection.Indexes.CreateOneAsync(Builders<Observer>.IndexKeys.Ascending(_ => _.MyId), new CreateIndexOptions { Unique = true });

foreach (var observer in _observers)
{
     observer.Timestamp = DateTime.Now;

     var res = await collection.FindAsync(o => o.MyId == observer.MyId);
     if (res==null ||res.Current == null) {
         await collection.InsertOneAsync(observer); //Part 1, fails 2nd time solved with res.MoveNextAsync()
     } 
     else
     {
            observer.ID = res.Current.Single().ID;
            var res2 = await collection.ReplaceOneAsync(o=>o.MyId==observer.MyId, observer);

            var res3 = await collection.FindAsync(o => o.MyId == observer.MyId);
            await res3.MoveNextAsync();
            Debug.Assert(res3.Current.Single().Timestamp == observer.Timestamp); //Part 2, Assert fails.
     }
}

Observer looks approximately like this:

public class Observer : IObserver
{
    [BsonId]
    public Guid ID { get; set; }

    public int MyId { get; set; }

    public DateTime Timestamp { get; set; }
}

The second time I run this with the exact same collection I unexpectedly get:

E11000 duplicate key error index: db.observers.$MyId_1  dup key: { : 14040 }

Edit:

Added original part two code: replacement.

Edit 2:

Now my code looks like this. Still fails.

var collection = storageClient.GetCollection<Observer>("gavagai_mentions");
    await collection.Indexes.CreateOneAsync(Builders<Observer>.IndexKeys.Ascending(_ => _.MyID), new CreateIndexOptions { Unique = true });
    foreach (var observer in _observers)
    {
    observer.Timestamp = DateTime.Now;

    // Create a BsonDocument version of the POCO that we can manipulate
    // and then remove the _id field so it can be used in a $set.
    var bsonObserver = observer.ToBsonDocument();
    bsonObserver.Remove("_id");

    // Create an update object that sets all fields on an insert, and everthing
    // but the immutable _id on an update.
    var update = new BsonDocument("$set", bsonObserver);
    update.Add(new BsonDocument("$setOnInsert", new BsonDocument("_id", observer.ID)));

    // Enable the upsert option to create the doc if it's not found.
    var options = new UpdateOptions { IsUpsert = true };
    var res = await collection.UpdateOneAsync(o => o.MyID == observer.MyID,
                          update, options);


    var res2 = await collection.FindAsync(o => o.MyID == observer.MyID);
    await res2.MoveNextAsync();
    Debug.Assert(res2.Current.Single().Timestamp == observer.Timestamp); //Assert fails, but only because MongoDB stores dates as UTC, or so I deduce. It works!!
    }

Solution

  • You can do this atomically with UpdateOneAsync by using the IsUpsert option to create the doc if it doesn't already exist.

    foreach (var observer in _observers)
    {
        // Create a BsonDocument version of the POCO that we can manipulate
        // and then remove the _id field so it can be used in a $set.
        var bsonObserver = observer.ToBsonDocument();
        bsonObserver.Remove("_id");
    
        // Create an update object that sets all fields on an insert, and everthing
        // but the immutable _id on an update.
        var update = new BsonDocument("$set", bsonObserver);
        update.Add(new BsonDocument("$setOnInsert", new BsonDocument("_id", observer.ID)));
    
        // Enable the upsert option to create the doc if it's not found.
        var options = new UpdateOptions { IsUpsert = true };    
        var res = await collection.UpdateOneAsync(o => o.MyId == observer.MyId,
                                                  update, options);
    }