public async Task AddOrUpdatePlayerGameAsync(string playerId, Player.Game game) { // First try to add it, if not there yet var updateResult = await _players.UpdateOne() .Filter(b => b.Match(p => p.Id == playerId && !p.Games.Any(g => g.Id == game.Id))) .Update(b => b.Modify(p => p.Push(g => g.Games, game))) .ExecuteAsync(); if (updateResult.MatchedCount == 0) // game is already part of Games array, so we need to update it { var command = _players.UpdateOne() .Filter(b => b.Match(p => p.Id == playerId)) .Options(b => b.WithArrayFilter($"{{ 'x._id' : '{game.Id}' }}")) .Update(b => b .Modify($"{{ $set : {{ 'Games.$[x].Status' : {(int)game.Status} }} }}") .Modify($"{{ $set : {{ 'Games.$[x].PlayerGameStatus' : {(int)game.PlayerGameStatus} }} }}")); if (game.StartedAt.HasValue) { command = command.Update(b => b.Modify($"{{ $set : {{ 'Games.$[x].StartedAt' : '{game.StartedAt.Value.ToIso()}' }} }}")); } if (game.EndedAt.HasValue) { command = command.Update(b => b.Modify($"{{ $set : {{ 'Games.$[x].EndedAt' : '{game.EndedAt.Value.ToIso()}' }} }}")); } updateResult = await command.ExecuteAsync(); if (updateResult.MatchedCount == 0) { throw new UpdateException(); } } }
public Task AddOrUpdatePlayerGameAsync(string playerId, Player.Game game) { if (Players.TryGetValue(playerId, out var player)) { player.Games.RemoveAll(g => g.Id == game.Id); player.Games.Add(game.Clone()); } if (player == null) { throw new UpdateException(); } return(Task.CompletedTask); }