如何从 MongoDB 聚合中的不同集合添加多个 $match 条件

amy*_*ous 2 join match mongodb aggregation-framework

我有 2 个不同的 MongoDB 集合 -员工部门都包含共同的deptid。我想加入这两个集合并从两个集合中添加多个 $match 条件。

雇员:

{
    Empid: 001
    Name: "John"
    Age: 41
    Location: "Belfast"
    deptid: "D101"
}
Run Code Online (Sandbox Code Playgroud)

部门:

{
    deptID: "D101"
    deptNM: "HR"
    deptPr: "O"
}
Run Code Online (Sandbox Code Playgroud)

询问:

db.getCollection('Employees').aggregate([
    { $match:{
        deptNM: "HR",
        Age : {$gt: 40}
       }
    },
    { $lookup: {
        from: "Dept",
        localField: "deptid",
        foreignField: "deptID",
        as: "HR EMP"
        }
     },
     { $project: {
         Empid: 1, Name: 1, Location: 1, deptNM: 1, deptPr: 1
         }
     }
])
Run Code Online (Sandbox Code Playgroud)

上面的查询不起作用,还有其他方法吗?

sri*_*asy 5

您的查询有几个问题 - 您无法在阶段deptNM: "HR"之前过滤字段,因为字段不是来自员工集合,请尝试以下查询:$lookupdeptNM

db.getCollection('Employees').aggregate([
    /** filter employees to retain whose age > 40 */
    {
        $match: {
            Age: { $gt: 40 }
        }
    },
    /** Get their respective dept */
    {
        $lookup: {
            from: "Dept",
            localField: "deptid",
            foreignField: "deptID",
            as: "HR_EMP"
        }
    },
    /** As lookup's field HR_EMP is an array unwind it to get it into object */
    { $unwind: '$HR_EMP' },
    /** filter depts for HR */
    { $match: { 'HR_EMP.deptNM': "HR" } },
    /** Project only needed fields or transform fields */
    {
        $project: {
            Empid: 1, Name: 1, Location: 1, deptNM: '$HR_EMP.deptNM', deptPr: '$HR_EMP.deptPr'
        }
    }])
Run Code Online (Sandbox Code Playgroud)

测试: MongoDB-Playground