MongoDB:按条件聚合布尔字段上的计数进行分组
我在Mongo有一个三列的收藏,比如:MongoDB:按条件聚合布尔字段上的计数进行分组,mongodb,nosql,mongodb-query,Mongodb,Nosql,Mongodb Query,我在Mongo有一个三列的收藏,比如: { "_id" : ObjectId("5b6db9e1d1b00b1b906c0225"), "ip" : "127.0.0.1", "hostFqdn" : "host-1", "active" : true }, { "_id" : ObjectId("5b6db9e1d1b00b1b906c0226"), "ip" : "127.0.0.2", "hostFqdn" : "host-1",
{
"_id" : ObjectId("5b6db9e1d1b00b1b906c0225"),
"ip" : "127.0.0.1",
"hostFqdn" : "host-1",
"active" : true
},
{
"_id" : ObjectId("5b6db9e1d1b00b1b906c0226"),
"ip" : "127.0.0.2",
"hostFqdn" : "host-1",
"active" : false
},
{
"_id" : ObjectId("5b6db9e1d1b00b1b906c0227"),
"ip" : "127.0.0.3",
"hostFqdn" : "host-2",
"active" : true
},
{
"_id" : ObjectId("5b6db9e1d1b00b1b906c0228"),
"ip" : "127.0.0.4",
"hostFqdn" : "host-2",
"active" : true
},
{
"_id" : ObjectId("5b6db9e1d1b00b1b906c0229"),
"ip" : "127.0.0.5",
"hostFqdn" : "host-2",
"active" : false
},
{
"_id" : ObjectId("5b6f61204b0f134f6635a74b"),
"ip" : "127.0.0.6",
"hostFqdn" : "host-3",
"active" : false
}
我需要选择最多有一个活动IP的所有hostFqdn(即,对于上述数据,响应将是host-1
和host-3
)
到目前为止,我得到的是:
db['hosts.status'].aggregate([[{
"$group": {
_id: "$hostFqdn",
"true": {
"$sum": {
"$cond": [{ "$lte": [{ "active": "$active" }, 1]}, 1, 0]
}
}
}
}]
但这将返回计数为0的所有三个hostsFqdn。有什么想法吗?你可以在下面试试
db.collection.aggregate([
{ "$group": {
"_id": "$hostFqdn",
"true": {
"$sum": {
"$cond": [{ "$eq": [ "$active", true ]}, 1, 0]
}
}
}}
])
美好的这将返回活动IP的数量,但是如果主机
mta-prod-3
,该怎么办?它不会返回零计数。好的,我们可以删除匹配阶段。我也更新了答案。太好了!非常感谢你,安东尼·温兹莱特
db.collection.aggregate(
// Pipeline
[
// Stage 1
{
$group: {
_id: '$hostFqdn',
status: {
$push: '$active'
}
}
},
// Stage 2
{
$project: {
v: {
$cond: {
if: {
$ne: [{
$indexOfArray: ['$status', true]
}, -1]
},
then: {
$sum: 1
},
else: 0
}
}
}
},
]
// Created with Studio 3T, the IDE for MongoDB - https://studio3t.com/
);