gpt4 book ai didi

javascript - 过滤子文档数组,如果为空则仍返回父数据

转载 作者:可可西里 更新时间:2023-11-01 09:59:11 25 4
gpt4 key购买 nike

我正在使用这个问题 How to filter array in subdocument with MongoDB 中的方法

它按预期工作,除非数组中的所有元素都不匹配测试。在这种情况下,我只会得到一个没有父数据的空数组。

示例数据

 {
"_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、电子邮件)和一个名为 vehicles 的属性,其中包含“事件”库存中列出的属性设置为 的所有车辆是的

我走了多远

这是我的查询。 (我使用 Mongoose 但主要使用原生 Mongo 功能)

      {
$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 以及他的电子邮件

没有车辆匹配时的期望输出

[{"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"
}
}
})

我们需要第一个条件跳过顶级文件,第二个条件跳过第二个级别,第三个条件 trim 车辆。 在这种情况下不需要 $unwind!

还有一件事:$redact 仅在 2.6 中可用

关于javascript - 过滤子文档数组,如果为空则仍返回父数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23636175/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com