结构如下:
{ "_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 } } }
我用聚合框架尝试了这个但是我有点卡住了.
以下查询:
db.book.aggregate([ { $unwind: '$bookings' }, { $project: { bookings: 1, rating: 1, month: { $month: '$bookings.startDate' } } }, { $group: { _id: { rating: '$rating', month: '$month' }, count: { $sum: 1 } } } ]);
会给你每个评级/月的结果,但它没有几个月的子文档.通常,您不能将值(例如月份nr)转换为键(例如month1) - 这是您可以在应用程序中轻松处理的内容.
以上聚合结果如下:
"result" : [ { "_id" : { "rating" : 2, "month" : 1 }, "count" : 1 }, { "_id" : { "rating" : 2, "month" : 12 }, "count" : 1 } ], "ok" : 1