【问题标题】:Mongo: How to count aggregation groups via Java's MongoTemplateMongo:如何通过 Java 的 MongoTemplate 计算聚合组
【发布时间】:2016-05-23 14:54:01
【问题描述】:

我有以下数据:

{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 的大小)

我需要如何调整我的聚合来实现这一点?

谢谢!

附言计数中忽略了大卫 - 正如预期的那样

【问题讨论】:

    标签: java mongodb aggregation-framework mongotemplate


    【解决方案1】:

    要获得最后一组的大小,您可以引入另一个最终的 $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")
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-14
      • 2020-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-28
      • 2012-12-17
      • 1970-01-01
      相关资源
      最近更新 更多