代码之家  ›  专栏  ›  技术社区  ›  Jeff Tian

如何在mongo数据库中进行联合表查询?

  •  1
  • Jeff Tian  · 技术社区  · 7 年前

    现在我有两个mongo系列:

    +--------------+--------------+
    |    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 回复  |  直到 7 年前
        1
  •  1
  •   Ashh    7 年前

    你可以在下面试试

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