1 year ago

#327800

test-img

user15963491

mongodb aggregation optimization: $sort and $group

For simple, I have a document like this:

name weight_1 weight_2
aaaa 1 5
bbbb 4 4
cccc 2 3
bbbb 3 2
cccc 5 1

My goal is to output a list and sort by weight_2 asc. If there are more than 1 records for each name, pick the smallest weight_1, so the result will be unique in name.

what I have done: Step 1. group by name, select grouped result by first record from weight_1 asc, it becomes

name weight_1 weight_2
aaaa 1 5
bbbb 3 2
cccc 2 3

Step 2. sort result from 1. by weight_2 asc, and it is my expected output:

name weight_1 weight_2
bbbb 3 2
cccc 2 3
aaaa 1 5

So I use the following mongodb aggregation pipeline:

[
  {
    $sort: { weight_1: 1 }
  },
  {
    $group: {
      _id: '$name',
      weight_1: { $first: '$weight_1' },
      weight_2: { $first: '$weight_2' }
    }
  },
  {
    $sort: { weight_2: 1 }
  }
]

which is working, but since the second $sort will not able to use any index, how can I improve performance for this scenario?

mongodb

query-optimization

nosql-aggregation

0 Answers

Your Answer

Accepted video resources