2017-10-11 52 views
0

我有2個mongo數據庫集合,我想加入他們,這對我使用查找 罰款,但在我做一個查找之前,我想分組和總結在一個集合具有條件Mongo在Java中查找總數組和條件

例:收集阿 ID, AMT, TYPE(1,2)

收集乙 ID, TAMT1, TAMT2,

現在上收集阿 if(TYPE == 1)Then Sum(amt)as TAMT1 if(TYPE == 2)Sum(AMT)as TAMT2 group by ID然後與集合B比較

任何一個提示/指導我如何做到這一點在java

+0

你到現在爲止嘗試過什麼? – sissy

+0

Aggregation agg = newAggregation它只接受一個不能通過的標準if else –

回答

0

我們可以使用聚合管道運營商$group$sum 總結基礎上,類型

讓集「一個」具有下列文件

{ "_id" : ObjectId("59de286a5d9132bd0bf3e870"), "amt" : 100, "type" : 1 } 
{ "_id" : ObjectId("59de286a5d9132bd0bf3e871"), "amt" : 200, "type" : 1 } 
{ "_id" : ObjectId("59de286a5d9132bd0bf3e872"), "amt" : 1000, "type" : 2 } 
{ "_id" : ObjectId("59de286a5d9132bd0bf3e873"), "amt" : 10000, "type" : 1 } 
{ "_id" : ObjectId("59de286a5d9132bd0bf3e874"), "amt" : 1000, "type" : 2 } 
{ "_id" : ObjectId("59de286a5d9132bd0bf3e875"), "amt" : 5000, "type" : 2 } 

蒙戈殼牌量q uery總結基於類型的文件是

db.a.aggregate([{$group:{_id:"$type", total:{$sum:"$amt"}}}]) 

在我們的樣本收集上述彙總查詢的結果是

{ "_id" : 2, "total" : 7000 } 
{ "_id" : 1, "total" : 10300 } 

請注意,您必須將殼查詢到Java查詢

轉換