mongodb aggregation sort

前端 未结 2 751
遇见更好的自我
遇见更好的自我 2020-12-28 12:56

I have a database of students and their contact details. I\'m trying to find out the postcode that houses the most students. The documents for the students look something li

相关标签:
2条回答
  • 2020-12-28 13:54

    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}}
    );
    
    0 讨论(0)
  • 2020-12-28 13:54

    I think your syntax is slightly wrong. Each aggregation operation in the pipeline should be its own document.

    db.students.aggregate( {$project: ...}, {$group: ...}, {$sort: ...} )
    

    In your case, it should be:

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

    I've tested it on a sample collection based on your schema and it works for me, sorting the grouped post codes by number of students, descending.

    0 讨论(0)
提交回复
热议问题