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 : []}]
實際輸出
[]