【发布时间】:2020-09-27 23:46:29
【问题描述】:
我是 mongodb 的新手。我正在尝试使用提供的搜索参数查找 2 个集合。
2 集合具有以下结构:
servicetypes
_id:ObjectId(5ede7d9552d21c000436ac52)
TypeId:"1"
ServiceTypeTitle:"Body and Frame"
__v:0
servicesubtypes
_id:ObjectId(5ede85003bdd1c0004f26e71)
TypeId:"1"
SubTypeId:"1"
ServiceSubTypeTitle:"Air dam repaired"
__v:0
我尝试使用正则表达式和管道,但没有达到我想要的效果。以下是我写的代码。
route.get('/FilterServices/:text', async (req, res) => {
var text = req.params.text
var list = await ServiceType.aggregate([
{
$lookup: {
from: "servicesubtypes",
localField: "TypeId",
foreignField: "TypeId",
as: "ServiceSubTypes"
}
},
{ "$match": { "ServiceSubTypes.ServiceSubTypeTitle": {$regex: text, $options:"i"} } }
]);
console.log(list)
res.send(list)
});
这会以下列方式返回数据:
[
{
_id: 5ede7d9552d21c000436ac52,
TypeId: '1',
ServiceTypeTitle: 'Body and Frame',
__v: 0,
ServiceSubTypes: [
[Object], [Object], [Object], [Object], [Object], [Object],
[Object], [Object], [Object], [Object], [Object], [Object],
...100 more items
]
},
{
_id: 5ede7d9652d21c000436ac53,
TypeId: '2',
ServiceTypeTitle: 'Brakes',
__v: 0,
ServiceSubTypes: [
[Object], [Object], [Object], [Object], [Object], [Object],
[Object], [Object], [Object], [Object], [Object], [Object],
...100 more items
]
},
{I have 5 more items in ServiceType but are not added due to regex}
]
使用上面的代码,如果它找到值,它将返回给我特定 ServiceType 的整个 ServiceSubTypes 数组。如果没有找到,则 ServiceType 不会添加到列表中。
如果找到匹配项,那么我只想要 ServiceSubTypes 数组中的特定记录。即
如果我的搜索参数是 sunvisor 那么结果应该是这样的
[
{
_id: 5ede7d9652d21c000436ac5a,
TypeId: '9',
ServiceTypeTitle: 'Vehicle',
__v: 0,
ServiceSubTypes: [
{
"_id": "5ede85683bdd1c0004f274d8",
"TypeId": "9",
"SubTypeId": "75",
"ServiceSubTypeTitle": "Right sunvisor replaced",
"__v": 0
},
{
"_id": "2ede8683dsaddc0004f2we4d8",
"TypeId": "9",
"SubTypeId": "75",
"ServiceSubTypeTitle": "Right sunvisor replaced",
"__v": 0
},
]
]
【问题讨论】:
标签: node.js mongodb mongoose mongodb-query aggregation-framework