2017-10-10 142 views
0

我有一個這樣的集合(摘要)。

{ 
    "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。 我不知道我是否正在這樣做。

謝謝!

+0

您可以發佈您預期的JSON結果?你希望只是{「id」:「dc1.1」,「clusters」:[{「id」:「cl1.1」,}]} – bgraham

+0

你的'$ elemMatch'指令使用''datacenters._id「 '但是正確的路徑(基於你提供的示例文件)是''datacenters.id'' – glytching

+0

'find'是查找文檔,而不是文檔的一部分。投影無條件地適用於所有房產,並且這裏不是正確的工具。您需要使用聚合來檢索子文檔。 –

回答

1

這是不可能的$elemMatch突出嵌套數組元素。

您可以在3.4服務器中嘗試下面的聚合。

使用$unwind幾次到達嵌套數組並應用$match來選擇嵌套數組元素。

db.summary.aggregate([ 
     { 
     "$match": { 
      "locations.datacenters._id": "dc1.1" 
     } 
     }, 
     { 
     "$unwind": "$locations" 
     }, 
     { 
     "$unwind": "$locations.datacenters" 
     }, 
     { 
     "$match": { 
      "locations.datacenters._id": "dc1.1" 
     } 
     }, 
     { 
     "$project": { 
      "locations.datacenters.clusters.servers": 0 
     } 
     } 
    ]) 

{"$project": {"locations.datacenters.clusters.servers": 0}}將刪除servers場,同時保持最終輸出的所有其他領域。

從文檔

如果指定_id以外的領域排除在外,你不能 採用任何其他$項目規範形式:如果排除 領域,即,你不能同時指定列入字段,重置現有字段的值 ,或添加新字段。

參考: https://docs.mongodb.com/manual/reference/operator/aggregation/project/#exclude-fields

+0

謝謝。它確實給了我資源來弄清楚如何處理我的要求。 –