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

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

问题描述

我正在员工表上执行聚合以获取一些带有投影的宿舍详细信息

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

      $query = ['_id' => new MongoDBBSONObjectID($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.

请帮忙!!!

推荐答案

使用 $unwindpreserveNullAndEmptyArrays 选项

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

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

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