Skip to content
Advertisement

How to return sorted array from object from MongoDB document?

I want to return an array, which is a property inside my mongo model/document, and I want that array to be sorted.

My MongoDB document looks like:

JavaScript

And I’m trying to return:

JavaScript

I have tried aggregation:

JavaScript

Advertisement

Answer

Mongo Playground reference Since $unwind returns the arrays as objects, we are using the $group to push the objects back into the items array

JavaScript

Output –

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement