2016-05-23 20 views
2

,我有以下數據:蒙戈:如何通過Java的MongoTemplate算匯聚組

{groupId: 1, name: Jon}, 
{groupId: 1, name: Dan}, 
{groupId: 2, name: Jon}, 
{groupId: 2, name: Ris}, 
{groupId: 3, name: David} 

我收到作爲輸入組ID的數組,我希望計算總爲那些DISTICT名稱金額組,我所定義的聚合代碼如下:

groupIds [] = {1,2} 

    Aggregation agg = newAggregation(
      match(Criteria.where("groupId").in((groupIds)), 
      group("name").count().as("total") 
    ); 

,但我得到含有數爲每名groupResult,即:

{name : Jon, total : 2} 
{name : Dan, total : 1} 
{name: Ris, total : 1} 

而其實我是想獲得總計數是= (實際上是上述groupResult的大小)

我怎麼需要調整我的聚集來實現這一目標?

謝謝!

p.s.大衛從計忽略 - 如預期

回答

1

爲了得到最後一組的大小,可以引入另一個決賽$group流水線階段,你可以使用一個null GROUP BY鍵組中的所有文檔,然後計算累計總和。

在蒙戈外殼,這將轉化

db.collection.aggregate([ 
    { "$match": { "groupId": { "$in": [1, 2] } } }, 
    { 
     "$group": { 
      "_id": "$name"    
     } 
    }, 
    { 
     "$group": { 
      "_id": null, 
      "total": { "$sum": 1 } 
     } 
    } 
]) 

隨着春天的數據,這應該遵循:

Aggregation agg = newAggregation(
    match(Criteria.where("groupId").in((groupIds)), 
    group("name"), 
    group().count().as("total") 
); 
+0

那正是我需要的!謝謝! – shemerk