2014-05-13 26 views
2

我使用的方法從這個問題How to filter array in subdocument with MongoDB篩選子文檔陣列,同時還返回如果空

它將按預期除非沒有數組中的元素的測試匹配父數據。在這種情況下,我只是得到一個沒有父數據的空數組。

樣本數據

{ 
    "_id": "53712c7238b8d900008ef71c", 
    "dealerName": "TestDealer", 
    "email": "[email protected]", 
    "address": {..}, 
    "inventories": [ 
     { 
      "title": "active", 
      "vehicles": [ 
      { 
       "_id": "53712fa138b8d900008ef720", 
       "createdAt": "2014-05-12T20:08:00.000Z", 
       "tags": [ 
       "vehicle" 
       ], 
       "opts": {...}, 
       "listed": false, 
       "disclosures": {...}, 
       "details": {...} 
      }, 
      { 
       "_id": "53712fa138b8d900008ef720", 
       "createdAt": "2014-05-12T20:08:00.000Z", 
       "tags": [...], 
       "opts": {...}, 
       "listed": true, 
       "disclosures": {...}, 
       "details": {...} 
      } 
     ] 
    }, 
    { 
     "title": "sold", 
     "vehicles": [] 
    } 
    ] 
} 

試圖做

在我的詢問,我想回報用戶(文件)的頂級信息(dealerName,電子郵件)和一個名爲屬性包含「有效」廣告資源中列出的所有媒介物的車輛設置爲true

多遠I GOT

這是我的查詢。 (我用的貓鼬,但大多使用本地蒙戈功能)

 { 
     $match: 
      email: params.username 
     } 
     { 
     $unwind: '$inventories' 
     } 
     { 
     $match: 
      'inventories.title': 'active' 
     } 
     { 
     $unwind: 
      '$inventories.vehicles' 
     } 
     { 
     $match: 
      'inventories.vehicles.listed': 
      $eq: true 
     } 
     { 
     $group: 
      _id: '$_id' 
      dealerName: 
      $first: '$dealerName' 
      email: 
      $first: '$email' 
      address: 
      $first: '$address' 
      vehicles: 
      $push: '$inventories.vehicles' 
     } 

的問題

起初,我還以爲我的查​​詢是很好,但是,如果沒有車輛被標記爲listed,查詢只是返回一個空數組。這是有道理的,因爲

 { 
     $match: 
      'inventories.vehicles.listed': 
      $eq: true 
     } 

不匹配任何東西,但我仍想獲得dealerName以及他的電子郵件

所需的輸出,如果沒有車輛MATCH

[{"dealerName": "TestDealer", "email": "[email protected]", vehicles : []}] 

實際輸出

[] 

回答

4

你可以使用$纂而不是$匹配在這種情況下,像這樣

db.collectionName.aggregate({ 
    $redact:{ 
    $cond:{ 
     if:{$and:[{$not:"$dealerName"},{$not:"$title"},{$eq:["$listed",false]}, 
     then: "$$PRUNE", 
     else: "$$DESCEND" 
    } 
    } 
}) 

我們需要第一個條件跳過頂層文件,第二個條件跳過第二級和第三個修剪車輛。 在這種情況下不需要$ unwind放棄

還有一件事:$ redact只有2.6可用