mongodb - $lookup with $if operator

mongodb - $lookup with $if operator

我正在构建一个辅助项目。如果某些条件匹配,我想在其中使用嵌套的 $lookup 和 $unwind 。我在下面创建了简单的原型。有些用户有号码,有些则没有号码。如果数字不为空或未定义,我想加入

这是代码 -

users.aggregate([



{
     
        $lookup: "number",
        localField:"user.number",
        foreignField:"name",
        as:"number"
     
   }
    {
                $unwind: {
                    path: "$number",
                    preserveNullAndEmptyArrays: true
                }
    }
    ,
   {
     
        $lookup: "countries",
        localField:"number.countrycode",
        foreignField:"name",
        as:"countries"
     
   },

   {

      $unwind:"countries",
      //preserveNullAndEmptyArrays

   },
   $project:{

       name:1,
       number:"$number.phoneNumber",
       countryCode:"$countries.countryCode"


    }
 ])

输出:

[{

name:"yashraj basan"
number:"123345677",
countryCode:"US"
},
{

name:"krutik basan"
number:"123345679",
countryCode:"FR"
}]

现在我得到所有有号码的用户,但我想要有号码和没有号码的用户

预期输出:

[{
    
    name:"yashraj basan"
    number:"123345677",
    countryCode:"US"
    },
    {
    
    name:"krutik basan"
    number:"123345679",
    countryCode:"FR"
    },
    {
      name:"dhruvam basan",
      number:"",
      countrycode:""
    },{
     name:"foo bar",
number:"",
countrycode:""
    }]

感谢您的所有意见。谢谢

没有必要 运行 $lookup 有条件地。您可以为每个用户执行此操作,但是当您使用 $unwind 时,您可以利用 preserveNullAndEmptyArrays 选项:

{
    $lookup: {
        from:"countries",
        localField:"user.number.countrycode",
        foreignField:"name",
        as:"countries"
    }
},
{
    $unwind: {
        path: "countries",
        preserveNullAndEmptyArrays: true
    }
}