Chandel
Chandel

Reputation: 1

Mongodb 3.2 : mongodb aggregation with $project before $lookup

I've a problem, actually I'm trying to join different collections for some operation, but I'm not able to get the result as both "BatchInfo" and "UserInfo" is coming as null.

The reason I'm doing "project" first is because I want to take out "Batch Id" and "User Id" from respective objects and then apply in respective "lookup" "foreignField". Also, I'm using mongo 3.2.

db.getCollection('coursecompletedfeedbacks').aggregate([

    {

        $project: {

           "BATCH" : 1,

           "FEEDBACK" : 1,

           "USER" : 1,

           "batchId" : "$BATCH._id",

           "userId" : "$USER._id"

        }

    },

    {

        $lookup:{

            from: "batches",           

            localField: "batchId",         

            foreignField: "_id",   

            as: "BatchInfo"           

        }

    },

    {

        $lookup:{

            from: "users",           

            localField: "userId",         

            foreignField: "_id",   

            as: "UserInfo"           

        }

    }

])

Upvotes: 0

Views: 258

Answers (1)

Jitendra
Jitendra

Reputation: 3185

Try as below:

db.getCollection('coursecompletedfeedbacks').aggregate([
    {
        $lookup:{
            from: "batches",           
            let: { bId: "$BATCH._id" },          
            pipeline: [
                {
                    $match: {
                        $expr: {
                            $eq: ["$_id", "$$bId"]
                        }
                    }
                },
            ],
            as: "BatchInfo"           
        }
    },
    {
        $lookup:{
            from: "users",           
            let: { uId: "$USER._id" },      
            pipeline: [
                {
                    $match: {
                        $expr: {
                            $eq: ["$_id", "$$uId"]
                        }
                    }
                },
            ],   
            as: "UserInfo"           
        }
    },
    {
        $project: {
           "BatchInfo" : 1,
           "UserInfo" : 1,
           ""FEEDBACK" : 1,
        }
    },
])

Upvotes: 0

Related Questions