MongoDB 统计多个字段
MongoDB counts multiple fields
这是输入集合:
{"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数据来实现这个?
{ "id" : "A1", "CountUp" : 2, "CountDown" : 1}
{ "id" : "A2", "CountUp" : 1, "CountDown" : 3}
这应该有效。
$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" } }}
这是输入集合:
{"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数据来实现这个?
{ "id" : "A1", "CountUp" : 2, "CountDown" : 1}
{ "id" : "A2", "CountUp" : 1, "CountDown" : 3}
这应该有效。
$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" } }}