Reputation: 4088
I have a collection with fields id, a-int, b-int, c-int, total-int
. I am trying to get a, b, c, total
but I end up getting just the sum of total
and rest of the field values are 0, 0, 0
. How do I fix this? Expected result from the data sample below 10, 20, 30, 300
Thanks
Data sample
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);
Upvotes: 0
Views: 1585
Reputation: 3931
I've got the result I think you wanted using the following:
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; " +
"}");
Note that what you need to do is tell the reduce function what to put into the a, b, and c fields as well as the total field.
This gave me a raw output of:
{ "a" : 10.0 , "b" : 20.0 , "c" : 30.0 , "total" : 300.0}
Since you haven't included the Grouped class, I'm not sure if this maps exactly into the object that you wanted, but it might point you in the right direction.
Upvotes: 1