Do $sort works for sub array document

mongo-java, mongodb

Solution

You weant to do the sort BEFORE you regroup:

db.orders.aggregate([ 
    { "$unwind" : "$items"} , 
    { "$sort" : { "items.sku" : 1}}, 
    { "$match" : { }} , 
    { "$group" : { "items" : { "$push" : { "sku" : "$items.sku"}} , "_id" : null}} ,
    { "$project" : { "_id" : 0 , "items" : 1}}
])

Problem

I have a collection which has a field of array kind. I want to sort on the basis of a field of sub-array but Mongo is not sorting the data. My collection is: ``` { "_id" : ObjectId("51f1fcc08188d3117c6da351"), "cust_id" : "abc123", "ord_date" : ISODate("2012-10-03T18:30:00Z"), "status" : "A", "price" : 25, "items" : [{ "sku" : "ggg", "qty" : 7, "price" : 2.5 }, { "sku" : "ppp", "qty" : 5, "price" : 2.5 }] } ``` My Query is: ``` db.orders.aggregate([ { "$unwind" : "$items"} , { "$match" : { }} , { "$group" : { "items" : { "$addToSet" : { "sku" : "$items.sku"}} , "_id" : { }}} , { "$sort" : { "items.sku" : 1}} , { "$project" : { "_id" : 0 , "items" : 1}} ]) ``` Result is: ``` "result" : [ { "items" : [ { "sku" : "ppp" }, { "sku" : "ggg" } ] } ], "ok" : 1 ``` } Whereas `"sku":"ggg"` should come first when it is ascending.

Original source