我有一个这样的集合(摘要)。
{
"id":"summaryid",
"locations": [
{
"id": "loc1",
"datacenters": [
{
"id": "dc1.1",
"clusters": [
{
"id": "cl1.1",
"servers": [
{
"id": "srvr1.1",
"services": [
{
"id": "srvc1.1"
}
]
}
]
}
]
},
{
"id": "dc1.2",
"clusters": [
{
"id": "cl1.2",
"servers": [
{
"id": "srvr1.2",
"services": [
{
"id": "srvc1.2"
}
]
}
]
}
]
}
]
},
{
"id": "loc2",
"datacenters": [
{
"id": "dc2.1",
"clusters": [
{
"id": "cl2.1",
"servers": [
{
"id": "srvr2.1",
"services": [
{
"id": "srvc2.1"
}
]
}
]
}
]
},
{
"id": "dc2.2",
"clusters": [
{
"id": "cl2.2",
"servers": [
{
"id": "srvr2.2",
"services": [
{
"id": "srvc2.2"
}
]
}
]
}
]
}
]
}
]
}
现在我只想要用于id为dc1.1的数据中心的集群。我想排除群集的服务器。
我已经尝试使用find查询与$ elemMatch和预测如下。
db.summary.find({}, {"locations": { $elemMatch: { "datacenters._id" :
"dc1.1" } }, "locations.datacenters.clusters":0,
"locations.datacenters.servers":0, "locations.datacentercount" : 0,
"locations.clustercount" : 0, "locations.servercount" : 0}).pretty()
我仍然得到所有的数据中心,而不是1匹配的id。 我不知道我是否正在这样做。
谢谢!
您可以发布您预期的JSON结果?你希望只是{“id”:“dc1.1”,“clusters”:[{“id”:“cl1.1”,}]} – bgraham
你的'$ elemMatch'指令使用''datacenters._id“ '但是正确的路径(基于你提供的示例文件)是''datacenters.id'' – glytching
'find'是查找文档,而不是文档的一部分。投影无条件地适用于所有房产,并且这里不是正确的工具。您需要使用聚合来检索子文档。 –