Search code examples
mongodbmongodb-queryaggregation-frameworkphp-mongodb

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


Solution

  • 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"
      }}
    ])