这是输入集合:
{"itemName" : "A1", "voteType" : "up"}
{"itemName" : "A1", "voteType" : "up"}
{"itemName" : "A1", "voteType" : "down"}
{"itemName" : "A2", "voteType" : "up"}
{"itemName" : "A2", "voteType" : "down"}
{"itemName" : "A2", "voteType" : "down"}
{"itemName" : "A2", "voteType" : "down"}
and so on...
有没有人知道如何使用聚合获取以下文档?
另外,我们如何使用Spring Data来实现它?
{ "id" : "A1", "CountUp" : 2, "CountDown" : 1}
{ "id" : "A2", "CountUp" : 1, "CountDown" : 3}
答案 0 :(得分:2)
这应该有效。
$cond
运算符可用于填充CountUp
和CountDown
字段。之后它只是对数据进行分组
{
$project:
{
itemName: 1,
countUp:
{
$cond: [ { $eq: [ "$voteType", "up" ] }, 1, 0 ]
},
countdown:
{
$cond: [ { $eq: [ "$voteType", "down" ] }, 1, 0 ]
}
}
},
{ $group : { _id : "$itemName", countUp: { $sum: "$countUp" }, countDown: { $sum: "$countdown" } }}