MongoDB aggregation - sum of array of nested objects

23 views Asked by At

I'm using mongo:latest Docker image (version mongo:7.0.7-jammy as of now)

I'm looking to calculate the sum of an array of nested objects that looks like this:

[
    {
        specificAmount: {
            amount: 200,
        }
    },
    {
        specificAmount: {
            amount: 300,
        }
    },
    ...
]

The way I'm tying to do this is:

xxx.aggregate([
    {
      $group: {
        _id: null,
        count: { $sum: 1 },
        totalSpecificAmount: { $sum: '$specificAmount.amount' || 0 },
      },
    },
 ]).toArray())

The counting works correctly, but the calculation of totalSpecificAmount does not - it always returns zero

How can I fix this?

1

There are 1 answers

0
yarex On

First of all - thank you @ray for the hint with $ifNull

The issue here was that specificAmount.amount is not a number as I specified in the question - they are strings and couldn't be summed up.

xxx.aggregate([
    {
      $group: {
        _id: null,
        count: { $sum: 1 },
        totalSpecificAmount: { 
            $sum: { $ifNull: [{ $toInt: '$specificAmount.amount' }, 0]},
        },
      },
    },
 ]).toArray())