Mongodb sort inner array

aggregation-framework, mongodb

Solution

You can do this by `$unwind`ing the `updates` array, sorting the resulting docs by `date`, and then `$group`ing them back together on `_id` using the sorted order.

db.servers.aggregate(
    {$unwind: '$service.apps.updates'}, 
    {$sort: {'service.apps.updates.date': 1}}, 
    {$group: {_id: '$_id', 'updates': {$push: '$service.apps.updates'}}}, 
    {$project: {'service.apps.updates': '$updates'}})

Problem

I've been looking for a while now and can't seem to sort an inner array and keep that in the doc that I'm currently working with. ``` { "service": { "apps": { "updates": [ { "n" : 1 "date": ISODate("2012-03-10T16:15:00Z") }, { "n" : 2 "date": ISODate("2012-01-10T16:15:00Z") }, { "n" : 5 "date": ISODate("2012-07-10T16:15:00Z") } ] } } } ``` So I want to keep the item to be returned as the service, but have my updates array sorted. So far with the shell I have: ``` db.servers.aggregate( {$unwind:'$service'}, {$project:{'service.apps':1}}, {$unwind:'$service.apps'}, {$project: {'service.apps.updates':1}}, {$sort:{'service.apps.updates.date':1}}); ``` Anyone think they can help on this?

Original source

Related problems