如何在Mongo DB中进行联合表查询?

时间:2018-10-08 10:17:57

标签: mongodb aggregation-framework

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

现在我有2个mongo集合:

  1. 公司
+--------------+--------------+
|    id        |     name     |
+--------------+--------------+
|     1        |   good name  |
+--------------+--------------+
|     2        |   bad name   |
+--------------+--------------+      
  1. 职位
+--------------+---------------+-------------------+
|      id      |    companyId  |      name         |
+--------------+---------------+-------------------+
|      1       |      1        |     bad position  |
+--------------+---------------+-------------------+
|      2       |      2        |    good position  |
+--------------+---------------+-------------------+

现在,我需要允许通过模糊匹配公司名称或职位名称来搜索职位。 例如,如果我通过名称“ 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 }]);

有人可以帮忙吗?预先感谢!

1 个答案:

答案 0 :(得分:1)

您可以尝试以下汇总

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