Sort collection on document ordernumber and sort subarray on subarray objectorder

I agree with John, the accepted answer is NOT the best way to do it at all. You never want to $unwind an array when it’s going to be followed by $group back into original documents.

In this case it causes additional issues like it won’t be able to use an index on documentordernumber if there is such an index (there should be to avoid having to sort in memory).

By the way, upcoming version 5.2.0 will have an implementation of $sortArray expression in aggregation so the workarounds John and I describe will not be necessary in the future. (See https://jira.mongodb.org/browse/SERVER-60967 and https://jira.mongodb.org/browse/SERVER-29425)

Once you’re on 5.2 the pipeline should be:

[ 
  {$sort:{ documentsordernumber : 1}}, 
  {$set:{ sublinks: {$sortArray:{ input:"$sublinks", sortBy:{sublinkid:1}}}}}
]

Asya

4 Likes