2016-09-08 5 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); 
    }) 
}; 

distiller/$ distillerはmongo ObjectIDです。リファレンス。

私は試合でやっているように、特定のIDで見つけたいと思っています。

次に、これらの一致した結果のうち、蒸留器IDがウイスキー内で同じである場合にそれらをグループ化してカウントしたいと考えます。 (各蒸留器のウイスキーの総数を数えようとする)。

期待通りに動作しますが、グループとカウントを含めると、countedDataに対して空の配列が返され続けます。

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 } 
}} 

私も試合を動かし、それがインデックスを使用していますので、最初のパイプライン・ステージで試合を行うことをお勧めしますコレクションに存在する。さらに、パイプラインでインデックスを使用することはできません。

関連する問題