Javascript 过滤子文档数组,如果为空,则仍返回父数据
我用的是这个问题的方法 除非阵列中没有任何元素与测试匹配,否则它将按预期工作。在这种情况下,我只得到一个没有父数据的空数组 样本数据Javascript 过滤子文档数组,如果为空,则仍返回父数据,javascript,arrays,mongodb,mongoose,Javascript,Arrays,Mongodb,Mongoose,我用的是这个问题的方法 除非阵列中没有任何元素与测试匹配,否则它将按预期工作。在这种情况下,我只得到一个没有父数据的空数组 样本数据 { "_id": "53712c7238b8d900008ef71c", "dealerName": "TestDealer", "email": "test@test.com", "address": {..}, "inventories": [ { "title": "active",
{
"_id": "53712c7238b8d900008ef71c",
"dealerName": "TestDealer",
"email": "test@test.com",
"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,email)和一个名为vehicles的属性,该属性包含“活动”库存中列出的属性设置为true
的所有车辆
我走了多远
[]
这是我的问题。(我使用Mongoose,但主要使用原生Mongo功能)
问题
起初,我认为我的查询很好,但是,如果没有任何车辆被标记为列出
,那么查询只返回一个空数组。这是有道理的,因为
{
$match:
'inventories.vehicles.listed':
$eq: true
}
与任何内容都不匹配,但我仍然希望获得DealName以及他的电子邮件
如果没有匹配的车辆,则需要输出
[{"dealerName": "TestDealer", "email": "test@test.com", vehicles : []}]
实际产出
[]
在这种情况下,可以使用$redact而不是$match,如下所示
db.collectionName.aggregate({
$redact:{
$cond:{
if:{$and:[{$not:"$dealerName"},{$not:"$title"},{$eq:["$listed",false]},
then: "$$PRUNE",
else: "$$DESCEND"
}
}
})
我们需要第一个条件跳过顶层文档,第二个条件跳过第二层,第三个条件修剪车辆在这种情况下,不需要$REWIND
还有一件事:$redact仅在2.6版本中可用,我认为这不起作用,因为
$cond
必须为真,根级和第二级才能达到第三级。此查询将在根级别修剪文档(它具有字段dealerName
,因此$cond
为false
)。唯一可行的方法是删除前两个条件,并将listed:true
添加到根级和第二级。