MongoDB Spring Data如何汇总来自多个字段的计数?

时间:2018-03-26 19:06:36

标签: java spring mongodb spring-data aggregation-framework

我们假设有一些这样的数据:

{
"orderId": 1,
    "manager" : [ 
        {
            "userId" : "UserId1"
        }
    ],
    "employee" : [ 
        {
            "userId" : "UserId3"
        }
    ]
}

{
"orderId": 2,
    "manager" : [ 
        {
            "userId" : "UserId1"
        }
    ],
    "employee" : [ 
        {
            "userId" : "UserId2"
        }
    ]
}

{
"orderId": 3,
    "manager" : [ 
        {
            "userId" : "UserId1"
        }
    ],
    "employee" : [ 
        {
            "userId" : "UserId2"
        }
    ]
}

结果应为:

{  
   "Agg":[  
      {  
         "userId":"UserId1",
         "total":3
      },
      {  
         "userId":"UserId2",
         "total":2
      },
      {  
         "userId":"UserId3",
         "total":1
      }
   ]
}

我想获得参与某个进程的userId的所有聚合计数。我需要通过来自" employee"的userId进行分组。和"经理"对象并加以总结。只有我可以做的是从一个列表中按userId分组:

Aggregation agg = newAggregation(
   match(Criteria.where("project").is("project")),
   unwind("manager"),
   group("manager.userId").count().as("total"),
   project("total").and("userId").previousOperation(),
   sort(Sort.Direction.DESC, "total")
);

如何汇总"经理"和"员工"字段?

2 个答案:

答案 0 :(得分:2)

使用$concatArrays

Aggregation agg = newAggregation(
   match(Criteria.where("project").is(project)),
   project("employee", "manager"),         
   project().and("manager").concatArrays("employee").as("merged"),
   unwind("merged"),
   group("merged.userId").count().as("total"),
   project("total").and("userId").previousOperation(),
   sort(Sort.Direction.DESC, "total")
);

答案 1 :(得分:1)

尝试类似:

 "$group' : { 
  '_id' : '$id', 
  'totalManager' : { '$sum' : '$manager.total' },
  'totalemployee' : { '$sum' : '$employee.total' }
}  }
 { "$project" : {
  'totalManager' : '$totalManager',
  'totalemployee' : '$totalemployee',
  'totalSum' : { '$add' : [ '$totalManager', '$totalemployee' ] },
 }