简体   繁体   中英

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.

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.

You could do something like this:

var query = Query<Entity>.EQ(e => e.Id, id);
var update = Update<Entity>.Set(e => e.Name, "Harry"); // update modifiers
collection.Update(query, update);

I hope you find this useful. Thanks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM