处理不存在的嵌入文档的展开

Handling unwind for the non existing embedded document

我正在对员工执行汇总 table 以获取一些带有投影的旅馆详细信息

      $query = ['_id' => new MongoDB\BSON\ObjectID($this->EmployeeId)];

    $pipeline = array(
         ['$match' => $query],
         [ '$addFields'=> [
          'assigned_master_keys'=> [
             '$cond'=> [
               'if'=> [
                       '$ne'=> [ [ '$type'=> '$assigned_master_keys' ], 'array' ]
                      ],
                     'then'=> [],
                     'else'=> '$assigned_master_keys'
                     ]
                 ]
        ]],          
        ['$unwind'=> '$assigned_master_keys'],
        ['$lookup' => [
                'from' => 'HostelTbl',
                'let' => [ 'hostelid' => '$assigned_master_keys.hostel_id' ],
                'pipeline' => [
                    ['$match' => [ '$expr'=> [ '$eq' => [ '$_id', '$$hostelid' ]]]],
                    ['$project' => [ 'Name'=> 1, 'MasterKeyDetails' => 1, '_id'=> 1]]
                 ],
                'as' => 'assigned_master_keys.hostel_id'
     ]],
    );

    $this->collection = $this->db->EmployeesTbl;
    $cursor = $this->collection->aggregate($pipeline);

以上代码适用于那些存在名称为 "assigned_master_keys" 的嵌入文档的员工,但不适用于那些 "assigned_master_keys" 不存在的员工。页面中断。如果我从上面的代码中删除 unwind,页面不会中断,但它也不会获取旅馆数据。

求助!!!

使用 $unwindpreserveNullAndEmptyArrays 选项

['$unwind'=> ['path' => '$assigned_master_keys', 'preserveNullAndEmptyArrays' => true ]]