本文介绍了按条件分组和计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将一组文档分组并根据它们的值对它们进行计数:
I'm trying to group a set of documents and count them based on their value:
{ item: "abc1", value: 1 }
{ item: "abc1", value: 1 }
{ item: "abc1", value: 11 }
{ item: "xyz1", value: 2 }
我想按 item
分组并返回 value
比 10
大多少次以及多少次小几倍:
I would like to group by item
and get in return a count of how many times the value
is bigger than 10
and how many times smaller:
{ item: "abc1", countSmaller: 2, countBigger: 1 }
{ item: "xyz1", countSmaller: 1, countBigger: 0 }
推荐答案
你需要的是 $cond
聚合框架的操作符.获得您想要的东西的一种方法是:
What you need is the $cond
operator of aggregation framework. One way to get what you want would be:
db.foo.aggregate([
{
$project: {
item: 1,
lessThan10: { // Set to 1 if value < 10
$cond: [ { $lt: ["$value", 10 ] }, 1, 0]
},
moreThan10: { // Set to 1 if value > 10
$cond: [ { $gt: [ "$value", 10 ] }, 1, 0]
}
}
},
{
$group: {
_id: "$item",
countSmaller: { $sum: "$lessThan10" },
countBigger: { $sum: "$moreThan10" }
}
}
])
注意:我假定 value
为数字而不是字符串.
Note: I have assumed value
to numeric rather than String.
输出:
{
"result" : [
{
"_id" : "xyz1",
"countSmaller" : 1,
"countBigger" : 0
},
{
"_id" : "abc1",
"countSmaller" : 2,
"countBigger" : 2
}
],
"ok" : 1
}
这篇关于按条件分组和计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!