Sum fields fields in one document into another document

I’m trying to build an aggregation that updates the players document with the points that they receive from the games that they play.

Here is the game document

    "_id": {
      "$oid": "63d00ec0771f06853d860862"
    },
    "game_id": 1,
    "winner": "player1",
    "con_id": "I",
    "map": "US",
    "player_results": [
      {
        "player-id": "player1",
        "totalMoney": 15,
        "totalPoints": 3
      },
      {
        "player-id": "player2",
        "totalMoney": 15,
        "totalPoints": 3,
        "winner": false
      }
    ]
  },
  {
    "_id": {
      "$oid": "63d00ec4dfdd8cb0e496422f"
    },
    "game_id": 2,
    "winner": "",
    "con_id": "I",
    "map": "EU",
    "player_results": [
      {
        "player-id": "player1",
        "totalMoney": 25,
        "totalPoints": 3,
        "winner": true
      },
      {
        "player-id": "player2",
        "totalMoney": 15,
        "totalPoints": 2,
        "winner": false
      }
    ]
  },

Here is the player documents in the same collection

{
    "_id": {
      "$oid": "63d01ae4b152a993335ef75e"
    },
    "player-id": "player1",
    "totalMoney": 0,
    "totalPoints": 0
  }

So in the ideal scenario it would update the player1 document to have totalPoints of 6 and totalMoney of 40.

I’m a little surprised that you keep players and documents in the same collection, but ok, let’s go with that.

Is there a way to tell which games are new? When you say “update” the players’ document to have total points - how is it known what games are already reflected in their totals? Like here the player has 0, but what if they had 6 points and 40 “money”? How do we know if that’s from this game or previous game?

Asya

Hi Asya,

i was planning on separating them into different collections but I was just doing some query testing today so they were in the same collection.

I was hoping to just total their score of all the games they were in, as there will not be very many games maybe 10 max. So I was going to re-total and update the document with the total result instead of tracking which had been counted.