Tom*_*mas 1 mongodb aggregation-framework
我尝试在MongoDB中计算不同的值,但我没有得到我期望的结果.
以下是数据示例:
{
"_id" : ObjectId("55d354b0d5cec8aad571b8fe"),
"version" : "0.4",
"scan-time" : {
"start" : 1439913109,
"end" : 1439913136
},
"services" : [
{
"service-type" : "SV1",
"service-version" : "V1",
"location" : {
"ipv4-address" : "192.168.1.1",
"protocol" : "tcp"
},
"classification-method" : "probed"
},
{
"service-type" : "SV1",
"service-version" : "V2",
"location" : {
"ipv4-address" : "192.168.1.2",
"protocol" : "tcp"
},
"classification-method" : "probed"
},
{
"location" : {
"ipv4-address" : "192.168.1.3",
"protocol" : "tcp"
},
"classification-method" : "probed",
"service-type" : "SV1",
"service-version" : "V3"
},
{
"service-type" : "SV2",
"service-version" : null,
"location" : {
"ipv4-address" : "192.168.1.4",
"protocol" : "tcp"
},
"classification-method" : "probed"
}
]
}
Run Code Online (Sandbox Code Playgroud)
我可以使用此查询列出所有不同的值:
db.collection.distinct("services.service-type")
Run Code Online (Sandbox Code Playgroud)
但是,我还需要一个计数.我尝试过这个,但它没有给出我想要的结果:
db.collection.aggregate(
[
{
$group : {
_id : "$services.service-type",
count: { $sum: 1 }
}
}
]
)
Run Code Online (Sandbox Code Playgroud)
我需要看到这个:
SV1: 3
SV2: 1
Run Code Online (Sandbox Code Playgroud)
MongoDB版本:
> db.version()
3.0.5
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助!
要在不同的查询中使用嵌套服务数组,您需要使用$ unwind来展开$ services
以下查询将输出不同的计数:
db.collection.aggregate([
{ $unwind: "$services" },
{
$group : {
_id : { "services-service-type": "$services.service-type" },
count: { $sum: 1 }
}
}
])
Run Code Online (Sandbox Code Playgroud)
输出:
{
"result" : [
{
"_id" : {
"services-service-type" : "SV2"
},
"count" : 1
},
{
"_id" : {
"services-service-type" : "SV1"
},
"count" : 3
}
],
"ok" : 1
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1654 次 |
| 最近记录: |