Hi @Andy_Bryan,
Yes $unwind
is a waste in this case because you want to sort an array of docs. You can also let the application layer do the job, but data manipulation is supposed to be done by the database by definition.
So there is 3 ways to sort an array of docs in MongoDB. The terrible way. The old school but OK way. And there is the pro way.
- The terrible way is $unwind + $sort + $group by _id with $push. It’s never a good idea to unwind an array and then reassemble the docs back again with a transformation. There is always a better way to avoid this mess in the memory. But in term of logic, it’s the easiest one to understand.
- The alternative solution to sort an array BEFORE v5.2 was this complicated pipeline that looks complex on paper but is a lot more memory efficient than the previous solution. You can also read more about it in @Paul_Done 's book here.
- Since 5.2, we have the pro version. Simple, elegant and optimized: $sortArray
Remember that the aggregation framework is Turing complete. You can literally do anything. I even wrote the Game of Life with it and @John_Page also mined bitcoins with it so… You can reduce your data manipulation in your back-end to the minimum if you can write the right query.
Cheers,
Maxime.