2013-01-13 30 views
0

我有一個字段集合id, a-int, b-int, c-int, total-int。我正在嘗試獲得a, b, c, total,但我最終得到的總和爲total,其餘字段值爲0, 0, 0。我該如何解決?從下面10, 20, 30, 300Groupby在MongoTemplate中返回空字段

感謝

數據樣本

id, a, b, c, total 
xid, 10, 20, 30, 100 
xid, 10, 20, 30, 200 


GroupBy groupBy = GroupBy.key("{a : 1, b : 1, c : 1}") 
    .initialDocument("{ total: 0 }") 
    .reduceFunction("function(obj, result) { result.total += obj.total; }"); 

GroupByResults<Grouped> results = mongoTemplate.group(Criteria.where("id").is(id), 
TABLE, groupBy, Grouped.class); 

回答

1

我已經有了結果的數據樣本預期的結果我想你想使用下列內容:

GroupBy groupBy = GroupBy.key("a", "b", "c") 
         .initialDocument("{ total: 0 }") 
         .reduceFunction("function(obj, result) { " + 
             " result.a = obj.a; " + 
             " result.b = obj.b; " + 
             " result.c = obj.c; " + 
             " result.total += obj.total; " + 
             "}"); 

注意什麼您需要做的是告訴reduce函數將a,b和c字段以及總字段放入哪些內容。

這給了我的原始輸出:

{ "a" : 10.0 , "b" : 20.0 , "c" : 30.0 , "total" : 300.0} 

既然你不包括分組類,我不知道這是否準確映射到您想要的對象,但它可能指向你在正確的方向。

+0

我有一個Group類來映射它。對於一個好的答案來說永遠不會太晚謝謝。 –

+0

什麼如果 ID,A,B,C,總 XID,10,20,30,100 XID,10,20,30,200 XID,10,10,30,300 XID,10,30, 30,400 我需要像 {「a」:10.0,「b」:20.0,「c」:30.0,「total」:300.0} {「a」:10.0,「b」:10.0, c「:30.0,」total「:300.0} {」a「:10.0,」b「:30.0,」c「:30.0,」total「:300.0} –