4

次のデータがあります。

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

入力として groupID の配列を受け取り、これらのグループの 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}

私は実際に= 3である合計数を取得したいのですが(これは実際には上記のgroupResultのサイズです)

それを達成するために集計をどのように調整する必要がありますか?

ありがとう!

ps Davidはカウントから無視されます-意図したとおり

4

1 に答える 1

2

最後のグループのサイズを取得するには、キーごとのグループを使用してすべてのドキュメントをグループ化し、累積合計を計算できる別の最終$groupパイプライン ステージを導入できます。null

mongo シェルでは、これは次のように変換されます。

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

Spring Data では、これは次のようになります。

Aggregation agg = newAggregation(
    match(Criteria.where("groupId").in((groupIds)),
    group("name"),
    group().count().as("total")
);
于 2016-05-23T15:08:31.210 に答える