Search code examples
javadatabasemongodbsortingaggregate

MongoDB how do I sort documents by the sum of two values?


I have "bank account" documents in a collection "economy" for a game in this format:

_id: ObjectId("62a5c5d741c1059e0f498c2c")
guild: 98525515134318336
user: 595415131438508070
balance: 156
bank: 100

I want to sort all of the documents that have the same guild value by the combined value of balance and bank (the total networth of that user) in descending order. I know that I need to use MongoDB aggregation, which I am familiar with, but I am not sure how to sort by two values summed together.

I am using MongoDB Java Driver but open to suggestions in the easier javascript form.


Solution

  • One option is to create a new field that sums both:

    db.collection.aggregate([
      {
        $addFields: {
          sum: {$add: ["$balance", "$bank"]}
        }
      },
      {
        $sort: {
          guild: 1,
          sum: -1
        }
      }
    ])
    

    See how it works on the playground example