按条件分组和计数
Posted
技术标签:
【中文标题】按条件分组和计数【英文标题】:Group and count with condition 【发布时间】:2015-07-22 01:01:34 【问题描述】:我正在尝试对一组文档进行分组并根据它们的值对它们进行计数:
item: "abc1", value: 1
item: "abc1", value: 1
item: "abc1", value: 11
item: "xyz1", value: 2
我想按item
分组,然后计算value
比10
大多少倍以及小多少倍:
item: "abc1", countSmaller: 2, countBigger: 1
item: "xyz1", countSmaller: 1, countBigger: 0
【问题讨论】:
【参考方案1】:如果有人正在寻找此场景的 Java 代码(根据我的需要更新字段):
Aggregation aggregation = Aggregation.newAggregation(
Aggregation.project("environment").and("success").applyCondition(ConditionalOperators.when(Criteria.where("deploymentStatus").is("SUCCESS"))
.then(1)
.otherwise(0)).and("failed").applyCondition(ConditionalOperators.when(Criteria.where("deploymentStatus").is("FAILURE"))
.then(1)
.otherwise(0)),
Aggregation.group("environment").sum("success").as("success").sum("failed").as("failed"));
【讨论】:
【参考方案2】:您需要使用$cond
运算符。这里0
的值小于10
和1
的值大于10
。这并不能完全为您提供预期的输出。也许有人会发布更好的答案。
db.collection.aggregate(
[
"$project":
"item": 1,
"value":
"$cond": [ "$gt": [ "$value", 10 ] , 1, 0 ]
,
"$group":
"_id": "item": "$item", "value": "$value" ,
"count": "$sum": 1
,
"$group":
"_id": "$_id.item",
"stat": "$push": "value": "$_id.value", "count": "$count"
]
)
输出:
"_id" : "abc1",
"stat" : [
"value" : 1,
"count" : 2
,
"value" : 0,
"count" : 2
]
"_id" : "xyz1", "stat" : [ "value" : 0, "count" : 1 ]
您需要将convert 您的值设置为integer
或float
【讨论】:
【参考方案3】:您需要的是聚合框架的$cond
运算符。获得您想要的东西的一种方法是:
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
是数字而不是字符串。
输出:
"result" : [
"_id" : "xyz1",
"countSmaller" : 1,
"countBigger" : 0
,
"_id" : "abc1",
"countSmaller" : 2,
"countBigger" : 2
],
"ok" : 1
【讨论】:
考虑到value
字段是一个字符串,因此您可能希望将该键值转换为数字。
@chridam,感谢您的评论。我在回答中添加了一条注释,说明我假设 value
字段为数字。我将把这部分作为练习留给 OP :)
我的错,我没有看到那张纸条,隐藏在代码之间:P以上是关于按条件分组和计数的主要内容,如果未能解决你的问题,请参考以下文章