Sum specific field in specific array position

Hi! How can I sum a specific field in an specific array position?
I have the field: “fee_details”: [{ “amount”: 300 }, { “amount”: 200 }] and I am using the $group operator and I want to sum just the fee_details[0].amount. How can I do that?
I saw on the web some people doing { $sum: “$specific_field.0.specific_property”} but it doesn’t work

Hi,
lets say you have the following collection

[
  {
    "key": 1,
    "fee_details": [{ "amount": 300 }, { "amount": 200 }]
  },
  {
    "key": 2,
    "fee_details": [{ "amount": 100 },{ "amount": 200 }]},
  {
    "key": 1,
    "fee_details": [{ "amount" : 50},{ "amount" : 200}]},
  {
    "key": 2,
    "fee_details": [{ "amount" : 30},{ "amount" : 200}]
  }
]

you want to group by key and sum the first fee_details for each key. The corresponding stage will be:

{
    $group: {
      _id: "$key",
      sum: {
        $sum: {
          $arrayElemAt: [
            "$fee_details.amount",
            0
          ]
        }
      }
    }
  }

Regards,

I’ve tried it, but it didn’t work. Can I use $sum in a string field? I’ve noticed the amount field type is ‘string’.
Btw, it’s a string type, but the value is a valid number, ofc

then, use $toInt

  {
    $group: {
      _id: "$key",
      sum: {
        $sum: {
          $toInt: {
            $arrayElemAt: [
              "$fee_details.amount",
              0
            ]
          }
        }
      }
    }
  }

for the input:

[
  {
    "key": 1,
    "fee_details": [
      {
        "amount": "300"
      },
      {
        "amount": 200
      }
    ]
  },
  {
    "key": 2,
    "fee_details": [
      {
        "amount": "100"
      },
      {
        "amount": 200
      }
    ]
  },
  {
    "key": 1,
    "fee_details": [
      {
        "amount": "50"
      },
      {
        "amount": 200
      }
    ]
  },
  {
    "key": 2,
    "fee_details": [
      {
        "amount": "30"
      },
      {
        "amount": 200
      }
    ]
  }
]

the stage results:

[
  {
    "_id": 2,
    "sum": 130
  },
  {
    "_id": 1,
    "sum": 350
  }
]

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.