mongodb - 如何在mongo db中进行联合表查询?
问题描述
我对 mongodb 很陌生,过去我使用 mysql 进行数据库查询。
现在我有 2 个 mongo 集合:
- 公司
+---------------+--------------+ | 编号 | 姓名 | +---------------+--------------+ | 1 | 好名字 | +---------------+--------------+ | 2 | 坏名声| +---------------+--------------+
- 职位
+--------------+---------------+------------------ -+ | 编号 | 公司ID | 姓名 | +--------------+---------------+------------------ -+ | 1 | 1 | 位置不好| +--------------+---------------+------------------ -+ | 2 | 2 | 好位置 | +--------------+---------------+------------------ -+
现在我需要允许通过模糊匹配名称(公司或职位名称)来搜索职位。例如,如果我按名称“good”搜索,结果应该是 2 个职位。因为对于职位 1,它的关联公司名称包含“good”,而对于职位 2,它自己的名称包含“good”。
那么我应该如何安排aggregation pipelines
来实现呢?
我尝试了以下方法,但它不起作用:
const lookup = {
from: "companies",
localField: "companyId",
foreignField: "_id",
as: "companies"
};
const match = {
$or: [
{
name: { $regex: companyOrPositionName }
},
{
"companies": { name: { $regex: companyOrPositionName } }
}
]
};
return await position.aggregate([{ $lookup: lookup }, { $match: match }]);
任何人都可以帮忙吗?提前致谢!
解决方案
您可以尝试以下聚合
position.aggregate([
{ "$lookup": {
"from": "companies",
"let": { "companyId": "$_id" },
"pipeline": [
{ "$match": { "$expr": { "$eq": [ "$_id", "$$companyId" ] } } },
{ "$project": { "name": 1 }}
],
"as": "companyName"
}},
{ "$unwind": "$companyName" },
{ "$match": {
"$or": [
{ "name": { "$regex": "good" }},
{ "companyName.name": { "$regex": "good" }}
]
}}
])
或者使用简单的find
查询
const companies = await Companies.find({ "name": { "$regex": "good" }})
const ids = companies.map(company => company._id)
position.find({
"$or": [
{ "companyId": { "$in": ids }},
{ "name": { "$regex": "good" }}
]
})
推荐阅读
- laravel - URI 必须是字符串或 UriInterface
- javascript - 如何提取两个单词之间的句子并排除特殊字符
- django - 使用功能视图添加到购物车功能在 django rest 框架中不起作用
- c# - 如何在 .NET Core 中显示本地时区
- c++ - 即使指针的 cout 指向内存地址,也显示“取消引用 null ptr”的代码。_malloca 用于分配内存
- javascript - 角度验证出错
- r - 我需要在图表上找到置信区间我有一个对警察和种族有 2 列置信度的数据集
- javascript - 从表单外部重置 React Native Formik 表单
- excel - ExecuteExcel4Macro ,有没有办法通过索引而不是 Application.ExecuteExcel4Macro 中的名称来引用工作表
- c# - 从下拉列表 Select2 中的多个值中获取选定值