Matthew Masurka
Matthew Masurka

Reputation: 375

Unable to retrieve $sum from MongoDB aggregate

In the query below, I successfully get the total length of all the contribution arrays, but I'm trying to also sum the contribution_receipt_amount field from each object in those arrays and its currently returning zero. What am I doing wrong?

 doc.aggregate(
        [
          { $unwind: '$contributions' },
          {
            $group: {
              _id: candidate.candidate_id,
              contributions: { $sum: 1 },
              total: { $sum: '$contribution_receipt_amount' }
            }
          }
        ],
        { allowDiskUse: true }
      )

The document looks like this:

{
    "_id" : "2015-05-31",
    "contributions" : [
    {
       "entity_type_desc" : "INDIVIDUAL",
       "contribution_receipt_amount" : 109.2,
     },
    {
       "entity_type_desc" : "INDIVIDUAL",
       "contribution_receipt_amount" : 105,
     }
  ]
},
{
    ...
}

And my output looks like this:

[ { _id: 'P60008885', contributions: 2, total: 0 } ]

Upvotes: 0

Views: 109

Answers (1)

Mani
Mani

Reputation: 1549

The catch here is the field contribution_receipt_amount is the child of contributions document. so you should refer with . notation to access the sub document elements.

"contributions" : {
    "entity_type_desc" : "INDIVIDUAL",
    "contribution_receipt_amount" : 109.2
}

Here is the updated query

doc.aggregate(
        [
          { $unwind: '$contributions' },
          {
            $group: {
              _id: candidate.candidate_id,
              contributions: { $sum: 1 },
              total: { $sum: '$contributions.contribution_receipt_amount' }
            }
          }
        ],
        { allowDiskUse: true }
      )

As suggested by Neil

doc.aggregate(
        [          
          {
            $group: {
              _id: candidate.candidate_id,
              contributions: { $sum: 1 },              
              total: { $sum: {$sum: "$contributions.contribution_receipt_amount"} }
            }
          }
        ],
        { allowDiskUse: true }
      )

Upvotes: 1

Related Questions