Yashraj basan
Yashraj basan

Reputation: 97

mongodb - $lookup with $if operator

I am building a side project. where I want to use nested $lookup and $unwind if certain condition match. I created simple prototype below. some users have numbers and some don't have numbers. I want to do join if the number is not null or undefined

here is the code -

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"


    }
 ])

Output:

[{

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

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

Right now i am getting all users who have numbers but i am want both users who have number and who don't have number

Expected output:

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

I appreciate all your inputs. thank you

Upvotes: 1

Views: 158

Answers (1)

mickl
mickl

Reputation: 49945

There's no need to run $lookup conditionally. You can do it for every user but then when you use $unwind you can take advantage of preserveNullAndEmptyArrays option:

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

Upvotes: 1

Related Questions