Mongodb 使用聚合框架按子文档字段分组
结构如下:Mongodb 使用聚合框架按子文档字段分组,mongodb,aggregation-framework,Mongodb,Aggregation Framework,结构如下: { "_id" : "79f00e2f-5ff6-42e9-a341-3d50410168de", "bookings" : [ { "name" : "name1", "email" : "george_bush@gov.us", "startDate" : ISODate("2013-12-31T22:00:00Z"), "endDate" : ISOD
{
"_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 } } }
]);
将为您提供每个评级/月的结果,但它不会在几个月内生成子文档。一般来说,您不能将值(如month nr)转换为键(如month1)——不过,这在应用程序中可能非常容易处理
上述汇总结果如下:
"result" : [
{
"_id" : {
"rating" : 2,
"month" : 1
},
"count" : 1
},
{
"_id" : {
"rating" : 2,
"month" : 12
},
"count" : 1
}
],
"ok" : 1