Aggregating (sum) multiple column in MongoDB

Hi there,
I’m trying to aggregate multiple columns in a single data source to create 3 sum values that I intent to pass to High Charts to create a leaderboard. However, I cannot get the sum command to return anything other than 0 after grouping.
Does anyone have any example queries of how this might be achieved?
Dab

Hi Dan,

Can you share the query you have tried? Just want to understand your data structure.

Thanks,
Deb

Hi Deb,

I’m trying to get the sum of the column t1 using variations of the query below but t1_total always returns 0 (indicating that it isn’t found):

  connection.find({
  aggregate: [
    {
      $group: {
        _id: '',
        t1_total:  {$sum: '$data.t1'},
        count: { $sum: 1 }
      }
    }
  ]
}).then(function (records) {
  console.log(records);
});

Hi Dan,

There is chance that the numbers stored in your column are stored as string and not numbers. You can just connect to the data source and see the format is in the console. For e.g. the number could be stored as “1” and not 1. In this case you will need to convert the string to int/double and then run the sum.

If it is indeed stored as numbers this example will work:

 connection
    .find({
      aggregate: [
        {
          $group: {
            _id: '',
            t1_total: { '$sum':  '$data.t1' }
          }
        }
      ]
    })
    .then(function(records) {
      console.log(records);
    });

Thanks,
Deb