2017-08-29 3 views
0

Ich habe die folgende Mongo-Abfrage. Mit diesem Beispiel erhalte ich ein Filialdokument (mit Lookup) "transport_type". Dieses Filialdokument hat viele Eigenschaften. Ich möchte nur die ID und den Namen. Wie kann ich $ project mit $ arrayElemAt und $ filter kombinieren? Im Moment gibt es alle Felder

$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 
       ] 
      ] 
     ]); 
    }); 

Antwort

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 
       ] 
      ] 
     ]); 
    }); 
Verwandte Themen