使用聚合框架按子文档字段进行分组

8

结构如下:

{
    "_id" : "79f00e2f-5ff6-42e9-a341-3d50410168de",
    "bookings" : [
        {
            "name" : "name1",
            "email" : "george_bush@gov.us",
            "startDate" : ISODate("2013-12-31T22:00:00Z"),
            "endDate" : ISODate("2014-01-09T22:00:00Z")
        },
        {
            "name" : "name2",
            "email" : "george_bush@gov.us",
            "startDate" : ISODate("2014-01-19T22:00:00Z"),
            "endDate" : ISODate("2014-01-24T22:00:00Z")
        }
    ],
    "name" : "Hotel0",
    "price" : 0,
    "rating" : 2 
}

现在,我想生成一份报告,告诉我预订了多少次,按预订月份分组(假设只有预订开始日期有关),并按酒店评级分组。
我希望答案是这样的:
{
    {
        rating: 0,
        counts: {
            month1: 10,
            month2: 20,
            ...
            month12: 7
        }
    }
    {
        rating: 1,
        counts: {
            month1: 5,
            month2: 8,
            ...
            month12: 9
        }
    }
    ...
    {
        rating: 6,
        counts: {
            month1: 22,
            month2: 23,
            ...
            month12: 24
        }
    }
}

我尝试使用聚合框架,但我有点卡住了。
1个回答

15

以下查询:

db.book.aggregate([
    { $unwind: '$bookings' },
    { $project: { bookings: 1, rating: 1, month: { $month: '$bookings.startDate' } } },
    { $group: { _id: { rating: '$rating', month: '$month' }, count: { $sum: 1 } } }
]);

将按评分/月份给您结果,但不会为每个月创建一个子文档。一般情况下,您不能将值(例如月份编号)转换为键(例如month1),但在您的应用程序中可能很容易处理此问题。

上述聚合结果如下:

"result" : [
    {
        "_id" : {
            "rating" : 2,
            "month" : 1
        },
        "count" : 1
    },
    {
        "_id" : {
            "rating" : 2,
            "month" : 12
        },
        "count" : 1
    }
],
"ok" : 1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接