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

Time:06-14

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.

CodePudding user response:

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

CodePudding user response:

By converting the javascript from nimrod serok, I was able to find the solution for MongoDB Java Driver!

public AggregateIterable<Economy> getLeaderboard(long guild) {
    return database.collection.aggregate(
            Arrays.asList(
                    Aggregates.match(Filters.eq("guild", guild)),
                    Aggregates.addFields(new Field("sum", Filters.eq("$add", Arrays.asList("$balance", "$bank")))),
                    Aggregates.sort(Sorts.descending("sum"))
            )
    );
}
  • Related