1
votes

I am using mongodb 3.6 version.

I have vehicle table with documents like

   {
    "_id": ObjectId("5b976220d2ccda12fc0050fb"),
    "VehicleNumber": "JK 678",
    "NumberOfSeats": "47",
   }
   {
    "_id": ObjectId("67976220d2ccda12fc005068"),
    "VehicleNumber": "JK 779",
    "NumberOfSeats": "47",
   }

I have route table with data like

    {
    "_id": ObjectId("5b7fb426d2ccda11fc005185"),
    "Name": "New Jersey City",
     "VehicleDetails": [
     {
        "VehicleEntryId": "b8d0d2b5-8f32-6850-4d79-34ed79138d6d",
        "VehicleId": ObjectId("5b976220d2ccda12fc0050fb"),
          ...
         "Status": "Active" 
      },
      {
      "VehicleEntryId": "b8d0d2b5-8f32-6850-4d79-34ed79138568",
      "VehicleId": ObjectId("67976220d2ccda12fc005068"),
        ...
       "Status": "Active" 
      } 
    ],
    ...
    }

I have written mongodb aggregation query like

       $cursor = $this->collection->aggregate([
    ['$match' => ["_id" => new MongoDB\BSON\ObjectID('5b7fb426d2ccda11fc005185')]],
    [
        '$addFields' => [
            'filteredIds' => [
                '$map' => [
                    'input' => '$VehicleDetails',
                    'as' => 'item',
                    'in' => [
                        '$cond' => [
                            ['$eq' => ['$$item.Status', 'Active']],
                            '$$item.VehicleId',
                            false
                        ]
                    ]
                ]
            ]
        ]
    ],

     array(
            '$lookup' => array(
                'from' => 'VehicleTbl',
                '$pipeline' => [
                       [ '$match'=> ["_id" => ['$in' => ['$$filteredIds'] ]]],
                 ],
                'as' => 'AllotedVehicleDetails'
            )
        ),
])->toArray();

Basically I am trying to fetch all assigned vehicle to a particular route. So I first fetch all the actively alloted vehicle ids by using $addFeilds operator and putting them in "filteredIds" then in lookup I am trying to fetch vehicle informations from vehicle table using pipeline. The above code throws error message 'Uncaught exception 'MongoDB\Driver\Exception\RuntimeException' with message '$lookup argument '$pipeline: [ { $match: { _id: { $in: [ "$$filteredIds" ] } } } ]' must be a string, is type array' in' line no 32.

Please help!!!

1

1 Answers

3
votes

use pipeline instead of $pipeline.

Example:

{
      $lookup : {
          'from' : 'vehicles',
           let : { localFilterIds : '$filteredIds'},
          pipeline : [
              {'$match'  : { $expr: {  '$in' : [ '$_id', '$$localFilterIds' ]  }} }
          ],
         'as' : 'AllotedVehicleDetails'
      }
  }

Note: This is tested in mongoDb GUI Robo 3T.