How Add Field To Each Document That Is The Max Value Of Field Across Documents

TL;DR Of What’s Wrong
Each of the documents in my collection has a field called “decimals”. I need to add a new field to each document that represents the maximum value across the working set of the “maximum” field. So if I have 4 documents with values 1,2,3,4. There’s be a new field in each document called “maxDecimals” equal to 4.

I’ve tried many different approaches but I’m a bit at a loss in how to do this exactly so I’d appreciate any help? I’ve considered worst case scenario to separate them into two different commands to the database but I’d really prefer not having to do that due to performance, resiliency and data consistency concerns.

What I’m trying to do
I’m trying to get the balance of a wallet, each document represents a some amount of funds that they have. The problem is that each document could have a different decimal amount (1, 2, 3, 4, etc.). Both for data formatting reasons and precision reasons, I cannot use the Decimal128 type in order to do the sum.

There are generally two mathematical ways to do what I want to do:

  • If I know the maximum decimal value I can use that in the aggregation pipeline below as a fixed value that all other numbers get casted to. Precision is only low when downcasting so that’s not a problem
  • If I can do a sum with the next document to be used available I can just upcast whichever one is lesser without having to know what the maximum decimal value in the whole set is.

How Can I Do Either Of These Using Aggregation Pipelines?

Current Aggregation Pipeline

[
  {
    $group:
      /**
       * _id: The id of the group.
       * fieldN: The first field name.
       */
      {
        _id: "$currency_code",
        maxDecimal: {
          $first: 2,
        },
        balance: {
          $sum: {
            $divide: [
              "$amount",
              {
                $pow: [
                  10,
                  {
                    $subtract: ["$decimals", 2],
                  },
                ],
              },
            ],
          },
        },
      },
  },
]

The problem with the above is that for any documents with a “decimals” value higher than 2 it would lose precision.