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