我在 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",
"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]
}
}
}}
])
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句