Mongodb mongo群与带条件计数
我试图对一组文档进行分组,并根据它们的值对它们进行计数。 比如说Mongodb mongo群与带条件计数,mongodb,mongodb-query,aggregation-framework,nosql,Mongodb,Mongodb Query,Aggregation Framework,Nosql,我试图对一组文档进行分组,并根据它们的值对它们进行计数。 比如说 { "_id" : 1, "item" : "abc1", "value" : "1" } { "_id" : 2, "item" : "abc1", "value" : "1" } { "_id" : 3, "item" : "abc1", "value" : "11" } { "_id" : 4, "item" : "abc1", "value" : "12" } { "_id" : 5, "item" : "xyz1", "
{ "_id" : 1, "item" : "abc1", "value" : "1" }
{ "_id" : 2, "item" : "abc1", "value" : "1" }
{ "_id" : 3, "item" : "abc1", "value" : "11" }
{ "_id" : 4, "item" : "abc1", "value" : "12" }
{ "_id" : 5, "item" : "xyz1", "value" : "2" }
在这里,我想按“项”分组,并得到一个计数,即“值”大于10的多少倍,以及小于10的多少倍。因此:
{ "item": "abc1", "countSmaller": 2, "countBigger": 1}
{ "item": "xyz1", "countSmaller": 1, "countBigger": 0}
使用$aggregate可以轻松实现普通计数,但如何实现上述结果?您需要使用运算符。这里的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 } ] }
您需要将值设置为integer
或float
您需要的是聚合框架的运算符。获得您想要的东西的一种方法是:
db.foo.aggregate([
{
$项目:{
项目:1,
lessThan10:{//如果值<10,则设置为1
$cond:[{$lt:[“$value”,10]},1,0]
},
大于10:{//如果值>10,则设置为1
$cond:[{$gt:[“$value”,10]},1,0]
}
}
},
{
$group:{
_id:“$item”,
countSmaller:{$sum:$lessThan10},
countbiger:{$sum:$moreThan10}
}
}
])
注意:我假设值为数字而不是字符串
输出:
{
“结果”:[
{
“_id”:“xyz1”,
"小数":一,,
“countbiger”:0
},
{
“_id”:“abc1”,
"小数":二,,
“countbiger”:2
}
],
“好”:1
}
如果有人正在寻找此场景的Java代码(根据我的需要更新字段):
请注意,值
字段是一个字符串,因此您可能希望将该键值转换为数字。@chridam,谢谢您的评论。我在回答中添加了一条注释,关于我假设值
字段为数字。我将把这部分作为练习留给OP:)我的错,我没有看到那张字条,可怕地藏在代码P之间
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"));