MongoTemplate中的Groupby返回空字段 [英] Groupby in MongoTemplate returning empty fields
问题描述
我有一个字段为id, a-int, b-int, c-int, total-int
的集合.我试图获取a, b, c, total
,但最终得到的只是total
的总和,其余字段值均为0, 0, 0
.我该如何解决?来自10, 20, 30, 300
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
谢谢
数据样本
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);
推荐答案
我得到了您认为想要使用以下结果的结果:
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; " +
"}");
请注意,您需要做的是告诉reduce函数将哪些内容放入a,b和c字段以及总字段中.
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.
这给了我原始输出:
{ "a" : 10.0 , "b" : 20.0 , "c" : 30.0 , "total" : 300.0}
由于您尚未包括Grouped类,因此我不确定这是否完全映射到您想要的对象中,但是它可能会为您指明正确的方向.
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.
这篇关于MongoTemplate中的Groupby返回空字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!