1

我有下面的代码片段应该使用弹簧数据的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 

这里取回帐户总数为等效蒙戈脚本,我使用AGG场返回在蒙戈外壳打印90

{ "$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。

回答

0

你得到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" } } } 
]) 

这将给你想要的结果。春季聚集相当于

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 
+0

谢谢chridam,我不知道为什么,但改变这样的代码后,给了我90:'聚集AGG = Aggregation.newAggregation( 组(“user.id”), 组()计数()作为( “总”))。。 AggregationResults result = mongos.aggregate(agg,this.getCollectionName(),AccountTotal.class);' – Hakan

+0

@Hakan这似乎也是正确的,我想这是因为聚合按用户ID分组所有文档但返回聚合方法中第二个参数指定的最终结果中的文档总数。你有没有尝试我的建议呢? – chridam

+0

是的,我尝试了,我通常忘记解释我的收藏内容,对不起,每个产品是购物清单的一部分包含用户数据,所以当我查询你的方法时,我得到每个产品的总数用户不是我所需要的:/ – Hakan