.NET Driver - Update the value of two items in a nested document in one operation

I am pretty sure this is what you want to do

var filter = Builders<Player>.Filter
            .Eq(r => r.Id, new ObjectId("65d46f1eaa08d32595abca1a"))
                     & Builders<Player>.Filter.ElemMatch(x => x.Inventory, Builders<PlayerInventoryItem>.Filter.Eq(x => x.Id, "cash"));
        
var update = Builders<Player>.Update
  // Set gold to 500
  .Set(x => x.Inventory.AllMatchingElements("gold").Qty, 500)
  // Set cash to 0
  .Set(x => x.Inventory.AllMatchingElements("cash").Qty, 0);

var arrayFilters = new[] {
  // match "gold" to anything in the list with the _id "gold"
  new JsonArrayFilterDefinition<Player>($@"{{""gold._id"": {{ $eq: ""gold""}} }}"),
  // match "cash" to anything in the list with the _id "cash"
  new JsonArrayFilterDefinition<Player>($@"{{""cash._id"": {{ $eq: ""cash""}} }}"),
};
        
var updateResult = await _collectionHelper.Players(_mongoClient).UpdateOneAsync(filter, update, new UpdateOptions {
  ArrayFilters = arrayFilters
});

1 Like