skip to Main Content

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.

2

Answers


  1. Chosen as BEST ANSWER

    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"))
                )
        );
    }
    

  2. 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

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