2017-08-29 70 views
0

我有以下的mongo查詢。通過這個例子,我得到了一個子文檔(帶查詢)「transport_type」。這個子文檔有很多屬性。我只想要id和名字。我怎樣才能將$ project與$ arrayElemAt和$ filter結合起來?現在它返回所有字段

$stations = Station::raw(function ($collection) use ($match){ 
     return $collection->aggregate([ 
      [ 
       '$lookup' => [ 
        'as' => 'transport_type', 
        'from' => 'transport_types', 
        'foreignField' => '_id', 
        'localField' => 'transport_type_id' 
       ] 
      ], 

      [ 
       '$match' => $match 
      ], 
      [ 
       '$project' => [ 
        'name' => 1, 
        'code' => 1, 
        'area_id' => 1, 
        'transport_type' => [ 
         '$arrayElemAt' => [ 
          [ 
           '$filter' => [ 
            'input' => '$transport_type', 
            'as' => 'transport_type_', 
            'cond' => [ '$eq' => [ '$$transport_type_.deleted_at', null ] ], 
           ] 
          ], 0 
         ] 
        ], 
        'active' => 1 

       ] 
      ], 
      [ 
       '$sort' => [ 
        'name' => 1 
       ] 
      ] 
     ]); 
    }); 

回答

0
$stations = Station::raw(function ($collection) use ($match){ 
     return $collection->aggregate([ 
      [ 
       '$lookup' => [ 
        'as' => 'transport_type', 
        'from' => 'transport_types', 
        'foreignField' => '_id', 
        'localField' => 'transport_type_id' 
       ] 
      ], 

      [ 
       '$match' => $match 
      ], 
      [ 
       '$project' => [ 
        'name' => 1, 
        'code' => 1, 
        'area_id' => 1, 
        'transport_type' => [ 
         '$let' => [ 
          'vars' => [ 
           'field' => [ 
            '$arrayElemAt' => [ 
             [ 
              '$filter' => [ 
               'input' => '$transport_type', 
               'as' => 'transport_type_', 
               'cond' => [ '$eq' => [ '$$transport_type_.deleted_at', null ] ] 
              ] 

             ], 0 
            ] 
           ] 
          ], 
          'in' => [ 
           ['id' => '$$field._id','name' => '$$field.name'] 
          ] 
         ] 
        ], 
        'active' => 1 

       ] 
      ], 
      [ 
       '$sort' => [ 
        'name' => 1 
       ] 
      ] 
     ]); 
    });