为不存在的嵌入式文档处理unwnd

时间:2018-11-11 17:11:32

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

我正在对employees表进行聚合,以通过投影来获取一些旅馆详细信息,例如

      $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,该页面不会中断,但也不会获取旅馆数据。

请帮助!!!

1 个答案:

答案 0 :(得分:1)

$unwindpreserveNullAndEmptyArrays选项一起使用

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