基于嵌入式文档的查找

Lookup on the basis of embedded documrnt

我有一个名为 assignmentTbl 的集合,一条记录存储为

    {
       _id : "6956GSVKU6535799",
       Type : "Project Abc",
       ...
       ...
       "TaskDetails"
        [
          { 
            "TaskId":"5759",
            "StudentId": ObjectId("5ab8845cff24ae1204000858"),
            ...
          },
          {
            "TaskId":"5659",
            "StudentId":  ObjectId("5ab8d7b1ff24ae1204000867"),
            ...
          }
          ...
        ]
    }

studentTbl 中的数据是这样的

   {
     "_id": ObjectId("5ab8d7b1ff24ae1204000867"),
     "profilePicture": "",
     "registration_temp_perm_no": "MGL-015",
     "admission_date": ISODate("2018-03-25T22:00:00.0Z"),
     "first_name": "Abrar",
     "middle_name": "",
     "last_name": "Khajwal",
     ...
   }
   ...
   ...

我想编写一个查询,它将从作业 table 中获取数据,并从 studentTbl 中获取一些学生信息(first_name 和 last_name)。请注意,studentTbl 中的所有其他字段都不是必需的。我无法在嵌入文档的基础上执行查找聚合。请帮助!!!

我已经尝试了下面的代码行,但它返回的是空的。

public function fetchAllAllotments() 
{
    $pipeline = array(
        array(
            '$lookup' => array(
                'from' => 'studentTbl',
                'localField' => '_id',
                'foreignField' => 'TaskDetails.StudentId',
                'as' => 'StudentsDetails'
            )
        ), 

        array('$match' => array('id' => new MongoDB\BSON\ObjectID($this->id)))
    );

    try
     {
        $cursor = $this->collection->aggregate($pipeline);
     } 
     catch (Exception $e) {

     }

   return $cursor->toArray();
} 

你需要先 $unwind 然后你可以申请 $lookup 阶段......而且你的 localField 应该是 TaskDetails.StudentIdforeignField 应该成为 _id

public function fetchAllAllotments() 
{
    $pipeline = array(
        array('$match' => array('id' => new MongoDB\BSON\ObjectID($this->id))),
        array('$unwind'=>'$TaskDetails'),
        array(
            '$lookup' => array(
                'from' => 'studentTbl',
                'localField' => 'TaskDetails.StudentId',
                'foreignField' => '_id',
                'as' => 'StudentsDetails'
            )
        )
    );

    try
     {
        $cursor = $this->collection->aggregate($pipeline);
     } 
     catch (Exception $e) {

     }

   return $cursor->toArray();
}