处理不存在的嵌入式文档的展开 [英] Handling unwind for the non existing embedded document

查看:84
本文介绍了处理不存在的嵌入式文档的展开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am performing aggregation on employees table to fetch some hostel details with projection like

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

The above code works fine for those employees where embedded document with name "assigned_master_keys" exists but not for those where "assigned_master_keys" does not exists. The page breaks. If I remove unwind from the above code, the page does not break but it does not fetch hostel data either.

请帮助!!!

推荐答案

$unwind preserveNullAndEmptyArrays 选项

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

这篇关于处理不存在的嵌入式文档的展开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆