mongodb聚合排序 [英] mongodb aggregation sort

查看:61
本文介绍了mongodb聚合排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个学生及其联系方式的数据库. 我正在尝试找出容纳最多学生的邮政编码. 学生的文件看起来像这样...

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 like this...

{学生代码:"smi0001",名字:"bob",姓氏:"smith",邮政编码: 2001}

{studentcode: 'smi0001', firstname: 'bob', surname: 'smith', postcode: 2001}

我认为我可以使用聚合框架通过执行类似的操作来找出学生最多的邮政编码.

I thought I could use the aggregation framework to find out the postcode with the most students by doing something like...

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

这按预期工作(返回邮政编码为_id,每个邮政编码中的学生人数为'students',但是如果我将$sort添加到管道中,则似乎尝试按整个学生集合而不是按$group操作的结果.

this works as expected (returns postcodes as _id and the number of students in each postcode as 'students', but if I add $sort to the pipeline it seems to try sorting by the whole student collection instead of the results of the $group operation.

我正在尝试的样子...

what I'm trying look like...

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

,但它返回整个集合,而忽略$project$group ... 我想念什么吗?我以为我可以按学生人数的降序排序并返回第一项. 预先感谢您的帮助.

but it returns the whole collection and disregards the $project and $group... Am I missing something? I thought I'd just be able to sort by descending number of students and return the first item. Thanks in advance for any help.

推荐答案

您几乎拥有了它...

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}}
);

这篇关于mongodb聚合排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆