Ayisha Najla
Ayisha Najla

Reputation: 51

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

Upvotes: 4

Views: 2640

Answers (2)

Favour Felix Chinemerem
Favour Felix Chinemerem

Reputation: 1408

To build on Ratan's answer,

How do you make your fields to be of similar type?


You can use the $toObjectId and $set operator to change your field values to a MongoDB ObjectId object and compare.

Model.aggregate([
  { $set: { local_id: { $toObjectId: '$local_id' } } },
  { $set: { foreign_id: { $toObjectId: '$foreign_id' } } },
])

In the example above, I am setting the value of local_id and foreign_id to be ObjectId for similar type comparison.

Upvotes: 0

Ratan Uday Kumar
Ratan Uday Kumar

Reputation: 6482

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

Upvotes: 5

Related Questions