skip to Main Content

Can you guys help me with this problem?

Example:
Data:

{
      _id: "63f69650e820990f82dca60b",
      ...,
      transactions: [
        {
          ...,
          fee: "100",
          ...
        },
        {
          ...,
          fee: "200",
          ...
        }
      ]
    }

I want to add a total_fee field to calculate total fee of all the transactions in a document.

I tried using

$addfields: {
  total_fee: {
    $sum: {$toInt: "$transactions.fee"}
  }
}

But mongo return error about can’t convert array to int

2

Answers


  1. When you specify "$transactions.fee", it resolves to an array of strings. $toInt doesn’t accept an array.
    You use $reduce to iterate through the array and convert each string to integer, before adding.

    db.collection.aggregate([
      {
        $addFields: {
          total_fee: {
            $reduce: {
              input: "$transactions.fee",   //1. Input is the array of strings
              initialValue: 0,              //2. Start 
              in: {                         //3. iterate though the array
                $add: [
                  "$$value",                //5. add the converted string to intermediate result, accessed using $value
                  {$toInt: "$$this"}        //4. use $this to access current value of the iteration, convert it to int
                ]
              }
            }
          }
        }
      }
    ])
    

    Demo

    Login or Signup to reply.
  2. Using $reduce is an overkill in my opinion. $map should be simpler and is certainly faster:

    db.collection.aggregate([
      {
        $addFields: {
          total_fee: {
            $sum: {
              $map: {
                input: "$transactions.fee",
                in: { $toInt: "$$this" }
              }
            }
          }
        }
      }
    ])
    

    Of course, the proper solution is to store numeric values as number rather than strings.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search