【问题标题】:Lookup on the basis of embedded documrnt基于嵌入式文档的查找
【发布时间】:2018-05-22 15:41:28
【问题描述】:

我有一个名为 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",
     ...
   }
   ...
   ...

我想编写一个查询,该查询将从作业表中获取数据,并从 studentTbl 中获取一些学生信息(名字和姓氏)。请注意,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();
} 

【问题讨论】:

  • 你可能需要先$unwindTaskDetails,因为它是一个数组而不是一个对象。
  • $unwind阶段放在$lookup之前
  • 能否请您告诉我,因为自己编写 mongo 查询非常困难

标签: mongodb mongodb-query aggregation-framework mongodb-php php-mongodb


【解决方案1】:

你需要先$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();
} 

【讨论】:

  • 它返回空数组
  • @NidaAmin 你的 localField 和 foreignField 被错误地提及...
  • 非常抱歉它仍然返回空数组
  • @NidaAmin array('$match' => array('id' => new MongoDB\BSON\ObjectID($this->id))) 当我删除它时,查询对我有用。
  • 我需要从 assignmentTbl 中获取特定记录(基于 _id)然后执行查找以便从 studentTbl 中获取一些字段
猜你喜欢
  • 1970-01-01
  • 2018-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-21
  • 1970-01-01
相关资源
最近更新 更多