mongodb join with different join field

oxf4rvwz  于 2023-08-04  发布在  Go
关注(0)|答案(1)|浏览(125)

我正在寻找一个简单的查询在mongoDB的帮助。我试过了,但都不管用。在搜索时,通常两个表具有相同的连接字段,或者它们没有条件。
我有两张table,
1.Employee(_id,name,deptid,country)
1.部门(_id,deptname)
现在我想加入,如在SQL

SELECT employee.name,department.deptname 
FROM employee, department
WHERE employee.deptid = department.id 
AND employee.country = 'India' 
AND department.deptname in ('IT', 'HR')

字符串

2ekbmq32

2ekbmq321#

MongoDB允许使用$lookup操作符(SQL LEFT OUTER JOIN子句)“连接”两个或更多个集合。在你的例子中,由于你想应用2o多个条件,我们需要运行多个连接条件

db.Employee.aggregate([
  {
    $match: {
      country: "India"
    }
  },
  {
    $lookup: {
      from: "Department",
      let: {
        deptid: {
          "$toObjectId": "$deptid"
        }
      },
      pipeline: [
        {
          $match: {
            deptname: { $in: ["IT","HR"]},
            $expr: {
              $eq: ["$_id", "$$deptid"]
            }
          }
        }
      ],
      as: "Department"
    }
  },
  {
    $unwind: "$Department"
  }
])

字符串
MongoPlayground

**注意:**如果Employee.deptid存储为ObjectId,则可以使用Correlated subquery

相关问题