【发布时间】:2017-11-20 10:20:59
【问题描述】:
我使用聚合来展开一个数组,并按数组的每个元素分组以求和一些对应的值。
我的收藏是这样的:
/* 1 */
{
"_id" : ObjectId("59ce411c2708c97154d1319b"),
"sourceMediumPath" : [
{
"nodeValue" : "(direct) / (none)"
},
{
"nodeValue" : "(direct) / (none)"
}
],
"totalConversions" : 1,
"totalConversionValue" : 171.6,
}
/* 2 */
{
"_id" : ObjectId("59ce411c2708c97154d136a0"),
"sourceMediumPath" : [
{
"nodeValue" : "google / cpc"
},
{
"nodeValue" : "(direct) / (none)"
},
{
"nodeValue" : "google / cpc"
}
],
"totalConversions" : 1,
"totalConversionValue" : 151.8,
}
我想按 sourceMedium.nodeValue 进行分组,并对“totalConverions”和“totalConversionValue”求和,而不考虑重复的元素。
例如通过使用展开、分组和求和:
aggregation = Aggregation.newAggregation(
Aggregation.unwind("sourceMediumPath"),
Aggregation.group("sourceMediumPath.nodeValue")
.sum("totalConversions").as(Variables.TOTAL_CONNVERSIONS)
.sum("TotalConversionValue").as(Variables.TOTAL_CONVERSION_VALUE),
Aggregation.project("sourceMediumPath.nodeValue")
.andInclude(Variables.TOTAL_CONNVERSIONS, Variables.TOTAL_CONVERSION_VALUE)
对于“nodeValue”:“(direct)/(none)”,TotalConversions 的总和等于 3,而“google / cpc”的总和等于 1。因为它在执行展开操作时重复了 totalConversions 和 totalConversions .
有任何解决方案可以忽略重复,每个文档只有一个值。
我该怎么做?
【问题讨论】:
标签: spring mongodb aggregation-framework spring-data-mongodb