【问题标题】:Aggregation inconsistently prints different value聚合不一致地打印不同的值
【发布时间】:2015-04-28 09:50:04
【问题描述】:

我有以下代码 sn-p 应该使用 spring-data-mongodb 检索帐户的总数

TypedAggregation<Account> agg = Aggregation.newAggregation(Account.class,
        group("user.id"),
        group().count().as("total"));

AggregationResults<AccountTotal> result = mongos.aggregate(agg, AccountTotal.class);
AccountTotal account = result.getMappedResults().get(0);
account.getTotal(); // should print 90 but prints 1

这是从我在 mongo shell 打印 90 中使用的 agg 字段返回的等效 mongo 脚本

{ "$group" : { "_id" : "$user.id"}} , 
{ "$group" : { "_id" :  null  , "total" : { "$sum" : 1}}}

> db.accounts.aggregate(
[
{ "$group" : { "_id" : "$user.id"}} , 
{ "$group" : { "_id" :  null  , "total" : { "$sum" : 1}}}
])

我在 Java 平台中获得 1 时实际上缺少什么。

编辑: 将前一个更改为以下一个后,我得到了预期的计数:

Aggregation agg = Aggregation.newAggregation( 
                   group("user.id"), 
                   group().count().as("total")); 
AggregationResults<AccountTotal> result = 
mongos.aggregate(agg, this.getCollectionName(), AccountTotal.class);

顺便说一句,谢谢@chridam。

【问题讨论】:

    标签: java spring mongodb aggregation-framework spring-data-mongodb


    【解决方案1】:

    你得到 1 的原因是因为当前聚合管道返回数组中按 user.id 分组的所有 90 个文档,每个文档可能总共有 1(我猜)。这行result.getMappedResults().get(0) 将获得聚合结果中的第一个元素,该元素的总数为 1。您尝试获取的总数是所有分组文档的总数,即聚合结果游标数组的长度。

    我相信您想按$user.id 字段对所有文档进行分组,获取每个分组结果的计数,然后再执行一次$group 操作以获得所有组计数的总和:

    > db.accounts.aggregate(
    [
        { "$group" : { "_id" : "$user.id", "count" : { "$sum" : 1 } } },
        { "$group" : { "_id" : null, "total" : { "$sum" : "$count" } } }
    ])
    

    这将为您提供所需的结果。 Spring 聚合等价物

    TypedAggregation<Account> agg = Aggregation.newAggregation(Account.class,
          group("user.id").count().as("count"),  
          group().sum("count").as("total"));
    
    AggregationResults<AccountTotal> result = mongos.aggregate(agg, AccountTotal.class);
    List<AccountTotal> accountCount = result.getMappedResults();
    (accountCount.get(0).total == 90); // should be true
    

    【讨论】:

    • 谢谢chridam,我不知道为什么,但是在更改这样的代码后给了我90:Aggregation agg = Aggregation.newAggregation( group("user.id"), group().count().as("total")); AggregationResults&lt;AccountTotal&gt; result = mongos.aggregate(agg, this.getCollectionName(), AccountTotal.class);
    • @Hakan 这似乎也是正确的,我认为这是因为聚合按用户 ID 对所有文档进行分组,但在最终结果中返回由第二个参数指定的文档总数聚合方法。顺便试一下我的建议了吗?
    • 是的,我试过了,我通常忘记解释我收藏的内容,很抱歉,购物清单中的每个产品都包含一个用户数据,所以当我查询你的方法时,我得到了每个用户的产品总数不是我需要的:/
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-18
    • 1970-01-01
    • 1970-01-01
    • 2012-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多