2013-02-07 108 views
12

我正在使用貓鼬在nodejs + mongodb項目上工作。現在我遇到了一個我不知道答案的問題。 我正在使用聚合框架來獲得分組結果。分組是在不包括時間數據字段的日期完成的,如「2013 02 06」。代碼如下所示:按貓鼬聚合框架中的日期排序

MyModel.aggregate([ 
      {$match: {$and: [{created_date: {$gte: start_date}}, {created_date: {$lte: end_date}}]}}, 
      {$group: { 
       _id: { 
        year: {$year: "$created_at"}, 
        month: {$month: "$created_at"}, 
        day: {$dayOfMonth: "$created_at"} 
       }, 
       count: {$sum: 1} 
      }}, 
      {$project: { 
       date: { 
         year: "$_id.year", 
         month:"$_id.month", 
         day:"$_id.day" 
       }, 
       count: 1, 
       _id: 0 
      }} 
     ], callback); 

分組結果是完美的,只是它們沒有排序。下面是輸出的一個例子:

[ 
    { 
     count: 1, 
     date: { 
      year: 2013, 
      month: 2, 
      day: 7 
     } 
    }, 
    { 
     count: 1906, 
     date: { 
      year: 2013, 
      month: 2, 
      day: 4 
     } 
    }, 
    { 
     count: 1580, 
     date: { 
      year: 2013, 
      month: 2, 
      day: 5 
     } 
    }, 
    { 
     count: 640, 
     date: { 
      year: 2013, 
      month: 2, 
      day: 6 
     } 
    } 
] 

我知道排序是通過將完成這件事:{$sort: val}。但是現在我不確定val應該是什麼,所以結果將按日期排序,因爲我的分組鍵是構成日期的3個值的對象。有誰知道這可以做到嗎?

編輯 有tryed這一點,它的工作:)

{$sort: {"date.year":1, "date.month":1, "date.day":1}}

回答

9

看來,這個問題有一個非常簡單的答案:)只需要通過這樣的多nesteed列進行排序:

{$sort: {"date.year":1, "date.month":1, "date.day":1}} 
+0

我認爲你也可以做'{$ sort:{「date」:1}} – knowbody

5

我被困在相同的問題,謝謝你的回答。 但我發現,你可以用更少的代碼

MyModel.aggregate([ 
      {$match: {$and: [{created_date: {$gte: start_date}}, {created_date: {$lte: end_date}}]}}, 
      {$group: { 
       _id: { 
        year: {$year: "$created_at"}, 
        month: {$month: "$created_at"}, 
        day: {$dayOfMonth: "$created_at"} 
       }, 
       count: {$sum: 1} 
      }}, 
      {$project: { 
       date: "$_id", // so this is the shorter way 
       count: 1, 
       _id: 0 
      }}, 
      {$sort: {"date": 1} } // and this will sort based on your date 
     ], callback); 
0

這,如果你只按日期排序,如果你有其他columsn進行排序工作得到同樣的結果。 YOu需要擴大_id

+0

修正組只有日期 –

+0

您應該更正您的答案與您的更正,而不是把它作爲一個評論。 – drneel