Mongo聚合框架,排序然后分组不起作用 [英] Mongo aggregation framework, Sort and then group not working

查看:182
本文介绍了Mongo聚合框架,排序然后分组不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试先按日期对数据进行排序,然后再对另一个字段进行分组. 它对我不起作用.

I am trying sort data by date first and then group on another field. It is not working to me.

我要回答的问题是:选择最新的唯一cid?

The question I am trying to answer is: Select the most recent distinct cid?

提供了以下数据:

db.summary.save({"lid" : 5, "date" : 5, "cid" : 2, "circles" : [ 2 ] })
db.summary.save({"lid" : 2, "date" : 2, "cid" : 1, "circles" : [ 2 ] })
db.summary.save({"lid" : 4, "date" : 0, "cid" : 3, "circles" : [ 2 ] })
db.summary.save({"lid" : 3, "date" : 3, "cid" : 2, "circles" : [ 2 ] })
db.summary.save({"lid" : 1, "date" : 1, "cid" : 1, "circles" : [ 2 ] })

db.summary.aggregate( {$match :{circles: 2}, $sort: {date: -1}, $group: {_id: '$cid'}} )

我首先在圈子中进行比赛, 然后是日期排序 然后在cid上分组

I am doing a match first on circles, then a sort on date, then a group on cid

我得到的结果:

{
    "result" : [
        {
            "_id" : 3
        },
        {
            "_id" : 1
        },
        {
            "_id" : 2
        }
    ],
    "ok" : 1
}

这是我的分析:

在按日期进行匹配或排序之前,数据为:

before matching or sorting by date, the data was:

"lid" : 5, "date" : 5, "cid" : 2
"lid" : 2, "date" : 2, "cid" : 1
"lid" : 4, "date" : 0, "cid" : 3
"lid" : 3, "date" : 3, "cid" : 2
"lid" : 1, "date" : 1, "cid" : 1

按日期排序后,数据集将为:

After sorting by date, the data set would be:

"lid" : 5, "date" : 5, "cid" : 2
"lid" : 3, "date" : 3, "cid" : 2
"lid" : 2, "date" : 2, "cid" : 1 
"lid" : 1, "date" : 1, "cid" : 1
"lid" : 4, "date" : 0, "cid" : 3

所以分组后,我期望的结果是:

So after grouping, the result I expect is:

{
    "result" : [
        {
            "_id" : 2
        },
        {
            "_id" : 1
        },
        {
            "_id" : 3
        }
    ],
    "ok" : 1
}

什么查询可以解决我的问题?

What query does solve my problem?

为什么当前查询对我不起作用?

Why is the current query not working for me?

推荐答案

当您在管道中的$sort之后执行$group时,先前的排序将丢失.您必须改为执行以下操作,以便在分组后可以找到要排序的日期:

When you $group after a $sort in the pipeline, the previous sort is lost. You'd have to do something like this instead so that the date you want to sort by is available after the grouping:

db.summary.aggregate(
    {$match: {circles: 2}},
    {$group: {_id: '$cid', date: {$max: '$date'}}},
    {$sort: {date: -1}});

结果:

[ { _id: 2, date: 5 }, 
  { _id: 1, date: 2 }, 
  { _id: 3, date: 0 } ]

如果要调整输出的形状,请在管道的末尾添加$project.

Add a $project to the end of the pipeline if you want to reshape the output.

这篇关于Mongo聚合框架,排序然后分组不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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