Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Project inside pipeline of lookup with local field and foriegn field not working

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 !!!

like image 525
Nida Amin Avatar asked Oct 24 '25 22:10

Nida Amin


1 Answers

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"
  }}
])
like image 89
Ashh Avatar answered Oct 27 '25 14:10

Ashh