Reputation: 4605
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.
Upvotes: 1
Views: 6005
Reputation: 2496
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.
Upvotes: -1
Reputation: 1606
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.
Upvotes: 4