[SERVER-42784] Allow sorting arrays as an aggregation operation Created: 12/Aug/19  Updated: 22/Aug/19  Resolved: 19/Aug/19

Status: Closed
Project: Core Server
Component/s: Aggregation Framework
Affects Version/s: None
Fix Version/s: None

Type: New Feature Priority: Major - P3
Reporter: Gabriel Belmonte Assignee: Asya Kamsky
Resolution: Duplicate Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Duplicate
duplicates SERVER-29425 Add an expression to sort an array Closed
Participants:

 Description   

Here's the use case.
I need a sorted array of elements within a document:

 

 
[
...
   { 
      $group: {
        "_id": "$athing",
        "anArray": {$push :"$aVal"}
      }
   },
   { $addFields : { "sortedArr" : { $sort :"$anArray" } } }, //something like this
...
]

Now, I could sort before the grouping, but that'll only work if the data set is small. If I have a much smalled subset of the data, sorting it would be much faster.

...
[
...
 { $sort : { "aVal" : -1 } }, //Does not work for very large data sets
 { 
   $group: {
     "_id": "$athing",
     "sortedArr": {$push :"$aVal"}
   }
 },
...
]



 Comments   
Comment by Gabriel Belmonte [ 22/Aug/19 ]

the example is vastly oversimplified (as examples are), in reality the field by which i need to sort is a result of a projection and a bit of manipulation, so the index might not work as well.

Comment by Asya Kamsky [ 19/Aug/19 ]

zhadow.of.light@gmail.com I closed this ticket as there is already one tracking this improvement but I wanted to point out two things:

 

  1. if you have an index to support the sort before the $group stage then it shouldn't be slow at all, in fact it should make the pipeline faster overall
  2. you can currently do the sort of an array yourself using existing aggregation expressions, an example of that is in this comment 
Comment by Asya Kamsky [ 19/Aug/19 ]

This looks like a duplicate of SERVER-29425 - closing.

Comment by Kelsey Schubert [ 16/Aug/19 ]

Hi zhadow.of.light@gmail.com,

Thanks for the feature suggestion. I've marked this ticket for consideration by our Query Team. Please continue to watch it for updates.

Kind regards,
Kelsey

Generated at Thu Feb 08 05:01:25 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.