4

I have written below lines of code for getting some specific fields inside lookup like

       $pipeline = array(
            array(
                '$match' => $query
            ),
            array(
                '$lookup' => array(
                    'from' => 'studentTbl',
                    'localField' => '_id',
                    'foreignField' => 'activity_details.activityId',
                     'pipeline' => [
                        ['$project' => [ '_id' =>  1.0, 'activity_details' => 1.0] ],
                     ],   
                    'as' => 'studentsOfActivities'
                )
            ),
           ....
           ....
        );

     return $this->db->activitiesTbl->aggregate($pipeline)->toArray();

Basically studentTbl has many fields and embedded documents. In the above code I am first fetching through lookup using foriegn and local fields and then determine which fields should be projected inside pipeline.

The above code is not working... Please help !!!

Nida Amin
  • 735
  • 1
  • 8
  • 28

2 Answers2

10

You can use below aggregation

db.collection.aggregate([
  { "$match": $query },
  { "$lookup": {
    "from": "studentTbl",
    "let": { "activityId": "$_id" },
    "pipeline": [
      { "$match": { "$expr": { "$in": ["$$activityId", "$activity_details.activityId"] }}},
      { "$project": { "activity_details": 1 }}
    ],
    "as": "studentsOfActivities"
  }}
])
Ashh
  • 44,693
  • 14
  • 105
  • 132
1

Hello here is the answer if you guys are looking query like: use project with local field and foreign field in-side aggregate method in MongoDB.

db.collection.aggregate([
                {
                    $lookup: {
                        from: "users", // collection name in db
                        localField: "user_id",
                        foreignField: "_id",                           
                        as: "userdata",                            
                    },

                },
                {$match :{_id: {$in:losers} }},
                {$project:
                    {
                      "answer":1,"_id":1,"win_status":1,"user_id":1,"user_id":1,
                        "userdata":{"name":1,"image":1,"email":1},
                    }
                }
            ])
Rohit Agrohia
  • 368
  • 3
  • 7