2014-05-13 15 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可用