2014-01-09 38 views
5

的結構如下:集團通過子文檔場使用聚合框架

{ 
    "_id" : "79f00e2f-5ff6-42e9-a341-3d50410168de", 
    "bookings" : [ 
     { 
      "name" : "name1", 
      "email" : "[email protected]", 
      "startDate" : ISODate("2013-12-31T22:00:00Z"), 
      "endDate" : ISODate("2014-01-09T22:00:00Z") 
     }, 
     { 
      "name" : "name2", 
      "email" : "[email protected]", 
      "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 
     } 
    } 
} 

我試圖與聚合框架,但我有點卡住了。

回答

11

下面的查詢:

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