Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

aggregate `$lookup` is not working in MongoDB

when i am using $lookup in my collections i am getting following output which is wrong

This the output:

{"_pipeline":[{"$project":{"fulldetails":{"$concat":["$associate_name"," ","$associate_no"]},"outlets":"$outl"}},{"$lookup":{"from":"outlets","localField":"_id","foreignField":"associate_id","as":"outl"}}],"options":{}}

And this is the query

  var data=Associate.aggregate([{
        $project: {
          "fulldetails": {
            $concat: ["$associate_name", " ", "$associate_no"]
          },
          "outlets": "$outl"
        }
      }, {
        $lookup: {
          from: "outlets",
          localField: "_id",
          foreignField: "associate_id",
          as: "outl"
        }
      }])

Thanks in advance

like image 428
Ayisha Najla Avatar asked Oct 15 '25 09:10

Ayisha Najla


1 Answers

Both foreign field and local field must be of same type than only $lookup will work

In your case

local field is _id

foreign field is associate_id

if _id is ObjectID and associate_id is ObjectID then only it will work

if _id is String and associate_id is String then only it will work

if _id is ObjectID and associate_id is String then it will not work

if _id is String and associate_id is ObjectID then it will not work

like image 118
Ratan Uday Kumar Avatar answered Oct 17 '25 22:10

Ratan Uday Kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!