匹配两个集合的查询

时间:2019-01-18 09:27:51

标签: mongodb mongoose

我有两个集合,一个是员工,另一个是薪水,我们有一个员工ID作为从薪水到员工薪水的参考。我想要一个查询,该查询可以为所有薪水中存在薪水的员工提供薪水明细,而薪水不存在的员工将返回零薪水。

简单来说,我需要在mongodb中进行正确的外部连接。 请帮助我。

谢谢。

1 个答案:

答案 0 :(得分:1)

//Employee Documents
/* 1 */
{
    "_id" : ObjectId("5c41aaa91d0b034e617effc0"),
    "emp_id" : 1
}

/* 2 */
{
    "_id" : ObjectId("5c41aaec1d0b034e617f0001"),
    "emp_id" : 2
}

/* 3 */
{
    "_id" : ObjectId("5c41aaf31d0b034e617f0009"),
    "emp_id" : 3
}

//Salary Documents:
{
    "_id" : ObjectId("5c41aac01d0b034e617effd4"),
    "emp_id" : 1,
    "salary" : 1000
}
**//Query**
db.employee.aggregate([
    {
        $lookup:{
            from: "salary",
            localField: "emp_id", //reference of employee collection
            foreignField: "emp_id",  //reference of salary collection
            as: "sal"
         }
    },{
       $unwind: {
             path: "$sal",
            preserveNullAndEmptyArrays: true //will return null if salary does not exist
        }
      },{
         $project:{
             emp_id: 1,
             salary:  { $ifNull: [ "$sal.salary", 0 ] } //will set to 0 if salary does not exist
             }  
       }]);

//Output
/* 1 */
{
    "_id" : ObjectId("5c41aaa91d0b034e617effc0"),
    "emp_id" : 1,
    "salary" : 1000
}

/* 2 */
{
    "_id" : ObjectId("5c41aaec1d0b034e617f0001"),
    "emp_id" : 2,
    "salary" : 0.0
}

/* 3 */
{
    "_id" : ObjectId("5c41aaf31d0b034e617f0009"),
    "emp_id" : 3,
    "salary" : 0.0
}