Search code examples
mongodbmongodb-queryaggregation-frameworkphp-mongodb

Handling unwind for the non existing embedded document


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);

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.

Please help!!!


Solution

  • Use $unwind with preserveNullAndEmptyArrays option

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