首页 > 解决方案 > 如何在mongo db中进行联合表查询?

问题描述

我对 mongodb 很陌生,过去我使用 mysql 进行数据库查询。

现在我有 2 个 mongo 集合:

  1. 公司
+---------------+--------------+
| 编号 | 姓名 |
+---------------+--------------+
| 1 | 好名字 |
+---------------+--------------+
| 2 | 坏名声|
+---------------+--------------+      
  1. 职位
+--------------+---------------+------------------ -+
| 编号 | 公司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 }]);

任何人都可以帮忙吗?提前致谢!

标签: mongodbaggregation-framework

解决方案


您可以尝试以下聚合

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" }}
  ]
})

推荐阅读