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 shell 中,这将转化为

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 回答