mongodb aggregation sort

You almost had it…

db.test.aggregate(
  {$group: {_id: '$postcode', students: {$sum: 1}}}, 
  {$sort: {_id: -1}}
);

gives (I added some test data matching your sample):

{
  "result" : [
    {
        "_id" : 2003,
        "students" : 3
    },
    {
        "_id" : 2002,
        "students" : 1
    },
    {
        "_id" : 2001,
        "students" : 2
    }
  ],
  "ok" : 1
}

You had an outer {} around everything, which was causing some confusion. The group and sort weren’t working as separate operations in the pipeline.

You didn’t really need the project for this case.

Update You probably want to sort by “students”, like so, to get the biggest zipcodes (by population) first:

db.test.aggregate(
  {$group: {_id: '$postcode', students: {$sum: 1}}}, 
  {$sort: {students: -1}}
);

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)