我有一個這樣的集合(摘要)。
{
"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'是查找文檔,而不是文檔的一部分。投影無條件地適用於所有房產,並且這裏不是正確的工具。您需要使用聚合來檢索子文檔。 –