2017-03-31 45 views
0

這個Meteor服務器代碼嘗試對文檔進行分組並按屬性「period」對其進行排序,但它沒有這樣做,任何想法如何解決它? THX如何對文件進行排序:聚合輸出

let invoicePopulation = UsageCol.aggregate([ 
     { 
      $match: { 
      action: {$in: ['a', 'b', 'c']}, 
      userId: doc.userId 
      } 
     }, 
     { 
      $group: { 
      _id: {period: "$period"}, 
      count: {$sum: 1} 
      } 
     }, 
     { 
      "$sort" : { 
      "period" : 1 
      } 
     } 
     ]); 

     //output 
     [{"_id":{"period":"42017"},"count":14},{"_id":{"period":"22017"},"count":1},{"_id":{"period":"32017"},"count":271}] 

//needs to be 
[{"_id":{"period":"22017"},"count":1},{"_id":{"period":"32017"},"count":271},{"_id":{"period":"42017"},"count":14}] 

回答

1

$group看起來很奇怪我。通常情況下,您希望在特定字段上進行分組,並且該字段將變爲您的_id(因爲該字段現在是唯一的)。

您的代碼中包含的方式是將子文檔設置爲_id的值。如果這真的是你想要的,那麼你的$sort應該是這個。

{ 
    $sort: { 
    "_id.period": 1 
    } 
} 

如果你是不是要建立一個_id子文檔,那麼你應該解決您的$group這樣。

let invoicePopulation = UsageCol.aggregate([ 
    { 
    $match: { 
     action: {$in: ['a', 'b', 'c']}, 
     userId: doc.userId 
    } 
    }, 
    { 
    $group: { 
     _id: "$period", 
     count: {$sum: 1} 
    } 
    }, 
    { 
    $sort : { 
     "period" : 1 
    } 
    } 
]); 
相關問題