如何按MongoDB中的特定月份进行分组?

时间:2018-02-24 07:52:37

标签: mongodb

这是一个集合:

{
    _id: "",
    name: "",
    date: ""
}

我逐年使用此代码:

db.collection.aggregate([{
    $group: {
        _id: {
            year: {
                $year: '$date'
            }
        }
    }
}]);

现在我想在那一年的特定月份进行分组。例如,每年的第二个月分组 这是一个例子:

{
    _id: "5a913bc6497a433de83f3689",
    name: "black",
    date: ISODate("2016-04-24T11:42:00.000Z")
},
{
    _id: "5a913bc6497a433de83f0679",
    name: "blue",
    date: ISODate("2017-03-15T11:42:00.000Z")
},
{
    _id: "5a913bc6497a433de83f0689",
    name: "red",
    date: ISODate("2017-04-12T11:42:00.000Z")
},
{
    _id: "5a913bc6497a433de83f0479",
    name: "green",
    date: ISODate("2017-04-15T11:42:00.000Z")
},
{
    _id: "5a913bc6497a433de83f0379",
    name: "yellow",
    date: ISODate("2018-03-04T11:42:00.000Z")
}

这是我想要的输出:

[
    {
        _id: "5a913bc6497a433de83f3689",
        name: "black",
        date: ISODate("2016-04-24T11:42:00.000Z")
    },
    {
        _id: "5a913bc6497a433de83f0679",
        name: "blue",
        date: ISODate("2017-03-15T11:42:00.000Z")
    }
]
[
    {
        _id: "5a913bc6497a433de83f0689",
        name: "red",
        date: ISODate("2017-04-12T11:42:00.000Z")
    },
    {
        _id: "5a913bc6497a433de83f0479",
        name: "green",
        date: ISODate("2017-04-15T11:42:00.000Z")
    },
    {
        _id: "5a913bc6497a433de83f0379",
        name: "yellow",
        date: ISODate("2018-03-04T11:42:00.000Z")
    }
]

每年的第4个月分组到第二年的第3个月。

1 个答案:

答案 0 :(得分:2)

您可以使用$month从日期开始获取月份(返回1到12之间的数字)。如果要将指定年度阈值的所有文档分组为特定月份,可以使用以下聚合:

db.col.aggregate([
    {
        $group: {
            _id: {
                $let: {
                    vars: { y: { $year: "$date" }, m: { $month: "$date" } },
                    in: { $cond: { if: { $gte: [ "$$m", 4 ] }, then: "$$y", else: { $subtract: [ "$$y", 1 ] } } }
                }
            },
            docs: {
                $push: "$$ROOT"
            }
        }
    }
])

基本上,如果月份大于或等于4(在这种情况下),那么它是当前年份,而不是之前的年份。