如何用mongodb排序$group聚合输出



我正在寻找按发件人的id排序的文档(电子邮件)的集合,然后返回发件人的id与最频繁的发送,限制为5。我相当接近,但与语法斗争,现在我需要对组进行排序。我理解,与mongodb的$group操作符不排序输出,我怎么能排序输出现在一旦它已经分组。我已经尝试将.sort()添加到查询序列的末尾,以及将输出设置为一个变量并调用.sort().limit(),但无济于事。

我有如下

cursor = db.emailcol.aggregate( 
    [{ $group : {_id : {emails_sent: "$sender_id"}, number : { $sum : 1} }},
        {$sort : {"_id.sender_id": 1}}
    ]
);
while ( cursor.hasNext() ) {
    printjson( cursor.next() );
};

返回:

{ "_id" : { "emails_sent" : "6" }, "number" : 3 }
{ "_id" : { "emails_sent" : "5" }, "number" : 2 }
{ "_id" : { "emails_sent" : "3" }, "number" : 1 }
{ "_id" : { "emails_sent" : "4" }, "number" : 2 }
{ "_id" : { "emails_sent" : "2" }, "number" : 1 }

我如何在分组的输出上运行排序方法,或者只是在查询中添加排序和限制?

聚合管道的排序阶段应该是:

{$sort : {"_id.emails_sent": 1}}

而不是:

{$sort : {"_id.sender_id": 1}}

作为$group阶段的输出,没有包含字段sender_id的子文档。要调试此类问题,查看管道每个阶段的输出将会有所帮助。

最新更新