2016-09-08 29 views
0
WhiskeySchema.statics.count = function (data){ 
    var distillerIds = data.map(function (a) { 
     return a.distiller._id; 
    }); 
    return Whiskey 
     .aggregate([ 
      { $group: { 
       // Group by fields to match on distiller 
       _id: { distiller: '$distiller'}, 
       // Count number of matching whiskeys for the group 
       count: { $sum: 1 } 
      }}, 
       { 
        $match: { 
         distiller : { 
          $in: distillerIds 
         } 
        } 
       } 
    ]) 
    .execAsync() 
    .then(function(countedData){ 
     console.log('counted data :', countedData) 
     return countedData; 
    }) 
    .catch(function(err){ 
     console.log('whiskey count err : ', err); 
    }) 
}; 

蒸餾器/ $蒸餾器是一個mongo ObjectID。一個參考。

我想找到特定的Ids,就像我在比賽中所做的一樣。

然後,在這些匹配結果中,我想在威士忌酒中的酒糟ID相同時對它們進行分組,並對它們進行計數。 (試圖計算每個蒸餾器的威士忌總數)。

匹配按預期工作,但是當我包括組和計數 - 我不斷得到一個空數組返回countingData。

counted data : [] 

回答

0

您匯聚的組部分不正確,將其更改爲:

.aggregate([ 
{ 
    $match: { 
     distiller : { 
      $in: distillerIds 
     } 
    } 
} 
{ $group: { 
    // Group by fields to match on distiller 
    _id: '$distiller', 
    // Count number of matching whiskeys for the group 
    count: { $sum: 1 } 
}} 

我也感動了比賽,這是最好做的比賽中,第一流水線級所以它使用索引目前收集。當進一步在管道中時,不能使用索引。

相關問題