4

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.

perror
  • 7,071
  • 16
  • 58
  • 85
Phalguni Mukherjee
  • 623
  • 3
  • 11
  • 29

1 Answers1

4

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}}
])
Sammaye
  • 43,242
  • 7
  • 104
  • 146
  • It doesn't work even than:rs0:PRIMARY> db.orders.aggregate([ ... { "$unwind" : "$items"} , ... { "$sort" : { "items.sku" : 1}}, ... { "$match" : { }} , ... { "$group" : { "items" : { "$addToSet" : { "sku" : "$items.sku"}} , "_id" : null}} , ... { "$project" : { "_id" : 0 , "items" : 1}} ... ]) { "result" : [{ "items" : [{ "sku" : "ppp" },{ "sku" : "ggg" }] } } – Phalguni Mukherjee Aug 01 '13 at 08:42
  • @PhalguniMukherjee I will need to test this, it should $push to set as such it should be ordered, theoretically – Sammaye Aug 01 '13 at 08:44
  • Just use `$push` instead of `$addToSet` in `$group`. – Yevgeniy Anfilofyev Aug 01 '13 at 09:00
  • @PhalguniMukherjee I would say it is the complexities of `$addToSet` it must be unordered – Sammaye Aug 01 '13 at 09:09