【问题标题】:Sort by date in mongoose aggregation framework在猫鼬聚合框架中按日期排序
【发布时间】:2013-01-22 17:10:59
【问题描述】:

我正在使用 mongoose 开发一个 nodejs+mongodb 项目。现在我遇到了一个我不知道答案的问题。 我正在使用聚合框架来获得分组结果。分组是在不包括时间数据字段的日期上完成的,例如:“2013 02 06”。代码如下所示:

MyModel.aggregate([
            {$match: {$and: [{created_date: {$gte: start_date}}, {created_date: {$lte: end_date}}]}},
            {$group: {
                _id: {
                    year: {$year: "$created_at"},
                    month: {$month: "$created_at"},
                    day: {$dayOfMonth: "$created_at"}
                },
                count: {$sum: 1}
            }},
            {$project: {
                date: {
                        year: "$_id.year",
                        month:"$_id.month",
                        day:"$_id.day"
                },
                count: 1,
                _id: 0
            }}
        ], callback);

分组的结果是完美的,只是它们没有排序。这是一个输出示例:

[
    {
        count: 1,
        date: {
            year: 2013,
            month: 2,
            day: 7
        }
    },
    {
        count: 1906,
        date: {
            year: 2013,
            month: 2,
            day: 4
        }
    },
    {
        count: 1580,
        date: {
            year: 2013,
            month: 2,
            day: 5
        }
    },
    {
        count: 640,
        date: {
            year: 2013,
            month: 2,
            day: 6
        }
    }
]

我知道排序是通过添加这个来完成的:{$sort: val}。但是现在我不确定val 应该是什么,因此结果将按日期排序,因为我的分组键是一个构造日期的 3 个值的对象。有谁知道如何做到这一点?

编辑 试过了,效果很好:)

{$sort: {"date.year":1, "date.month":1, "date.day":1}}

【问题讨论】:

    标签: sorting mongoose aggregation-framework


    【解决方案1】:

    看来这个问题有一个非常简单的答案:) 只需要像这样按多个嵌套列排序:

    {$sort: {"date.year":1, "date.month":1, "date.day":1}}
    

    【讨论】:

    • 我觉得你也可以{$sort: {"date": 1} }
    【解决方案2】:

    我遇到了同样的问题,谢谢你的回答。 但我发现你可以用更少的代码得到同样的结果

    MyModel.aggregate([
                {$match: {$and: [{created_date: {$gte: start_date}}, {created_date: {$lte: end_date}}]}},
                {$group: {
                    _id: {
                        year: {$year: "$created_at"},
                        month: {$month: "$created_at"},
                        day: {$dayOfMonth: "$created_at"}
                    },
                    count: {$sum: 1}
                }},
                {$project: {
                    date: "$_id", // so this is the shorter way
                    count: 1,
                    _id: 0
                }},
                {$sort: {"date": 1} } // and this will sort based on your date
            ], callback);
    

    【讨论】:

      【解决方案3】:

      如果您仅在有其他列要排序的情况下按日期排序,这将起作用。你需要扩展_id

      【讨论】:

      • 你应该用你的更正来更新你的答案,而不是把它作为评论。
      猜你喜欢
      • 2015-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-15
      • 1970-01-01
      • 2021-01-14
      相关资源
      最近更新 更多