$unwind 和 $lookup php mongodb

$unwind and $lookup with php mongodb

我在 mongodb 有一个 table TblStudent 喜欢

       {
      "_id": ObjectId("5baa85041d7859f40d000029"),
       "Name": "John Doe",
       "RollNo": 12,
       "Class": "Ist"
        ....
       }

我还有一个 table TblRoute 喜欢

   {
   "_id": ObjectId("5baa818d1d78594010000029"),
   "Name": "New york City",
   "StopDetails": [
   {
    "StopId": "abc777",
    "Name": "Block no 3"
   },
   {
   "StopId": "abc888",
   "Name": "Block no 4"
   }
 ],
"NumberOfSeats": "10",
"StudentDetails": [
 {
   "StudentId": ObjectId("5baa85041d7859f40d000029"),
   "VehicleId": "7756"
  },
  {
   "StudentId": ObjectId("5baa85f61d7859401000002a"),
   "VehicleId": "7676"
 }
 ]
}

我正在使用 mongodb 3.6 平台。在获得在线帮助后,我正在使用以下代码行!!!

      $query = ['_id' => new MongoDB\BSON\ObjectID($this->id)];
      $cursor = $this->db->TblRoute->aggregate([
      ['$match' => $query],
      ['$lookup' => [
         'from' => "TblStudent",
         'let' => ['studentid' => '$StudentDetails.StudentId'],
         'pipeline' => [
         ['$match' => ['$expr'=> ['$in' => ['$_id','$$studentid' ]]]],
         ['$project' => ['Name'=> 1,'RollNo' => 1, '_id'=> 1]]
         ],
         'as' => 'studentObjects',
       ]],
       ['$unwind'=> '$studentObjects' ],
        // Group back to arrays
       [ '$group'=> [
               'StudentDetails.StudentId'=> '$_id',
                'StudentDetails.StudentData'=> [ '$push'=> '$studentObjects' ]
       ]]

     ]);

它正在抛出错误消息未捕获的异常 'MongoDB\Driver\Exception\RuntimeException',消息为“字段 'StudentDetails.StudentId' 必须是累加器对象”

基本上我想使用查找聚合从另一个 table 获取数据。于是经过网上求助和进一步研究,才写出了上面的代码。这里的主要问题是 $unwind 语句之前的代码将输出生成为单独的数组。如果我们在 $lookup 中写入 'as' => 'StudentDetails.studentObjects' ,数据将被新数据覆盖,从而导致其他字段(如 vehicleid 等)丢失。我想要 保存它们。因此,经过研究,我尝试添加 $group 以将其放回 StudentDetails 嵌入式文档中。

期望的输出

        {
"_id": ObjectId("5baa818d1d78594010000029"),
"Name": "New york City",
"StopDetails": [
     .....
  ],
   "StudentDetails": [
   {
   "StudentId": ObjectId("5baa85041d7859f40d000029"),
   "VehicleId": "7756",
   "StudentData": [
      "Name": ..
      "RollNo":...
    ]
    },
    {
    "StudentId": ObjectId("5baa85f61d7859401000002a"),
    "VehicleId": "7676",
     "StudentData": [
      "Name": ..
      "RollNo":...
    ]
   }
   ]
  }

请帮我解决问题

你可以这样做

$cursor = $this->db->TblRoute->aggregate([
  [ "$match" => $query ],
  [ "$unwind": "$StudentDetails" ],
  [ "$lookup" => [
    "from" => "TblStudent",
    "let" => [ "studentid" => "$StudentDetails.StudentId" ],
    "pipeline" => [
      [ "$match" => [ "$expr"=> [ "$eq" => [ "$_id", "$$studentid" ]]]],
      [ "$project" => [ "Name"=> 1, "RollNo" => 1, "_id"=> 1 ]]
    ],
    "as" => "StudentDetails.StudentId"
  ]],
  [ "$unwind": "$StudentDetails.StudentId" ],
  [ "$group"=> [
    "_id"=> "$_id",
    "Name": [ "$first"=> "$Name" ],
    "StopDetails": [ "$first"=> "$StopDetails" ],
    "StudentDetails"=> [ "$push"=> "$StudentDetails" ]
  ]]
])