Search code examples
c#mongodbmongodb-querymongodb-.net-drivernosql

Updating a single element in a nested list with official C# MongoDB driver


I have a simple game with multiple rounds and I want to update the most recent round:

class Game
{
    public ObjectId Id { get; set; }
    public List<Round> Rounds { get; set; }
}

class Round
{
    public int A { get; set; }
    public int B { get; set; }
}

How can I do the equivalent of games.Rounds.Last().A = x using the official MongoDB C# driver?

Edit: Added Round.B. Note that in this case, both A and B may be updated concurrently so I cannot save back the entire document. I only want to update the A field.


Solution

  • If you're using the drivers with LINQ support, then I suppose you could do this:

    var last = collection.AsQueryable<Game>().Last();
    last.A = x;
    collection.Save(last);
    

    I imagine it wouldn't be as efficient as a hand-coded update statement, but this does functionally mirror your javascript version for the most part.

    Edit: Without LINQ, and doing a subset update

    var query = Query.EQ("_id", MongoDB.Bson.BsonValue.Create(games.Id);
    var update = Update.Set("Rounds." + games.Rounds.Length - 1 + ".A", MongoDB.Bson.BsonValue.Create(x));
    
    Collection.Update(query, update);
    

    Not so pretty looking, but you can index into an array by the number in Mongo, so you'd miss out on the case where a new Round was added to the game before you update.