Search code examples
mongodbphp-mongodb

projection in php mongodb


I have a collection with document like

{
 "_id": ObjectId("5b4dd622d2ccda10c00000f0"),
 "Code": "Route-001",
 "Name": "Karan Nagar - Jawahar Nagar",
 "StopsDetails": [
  {
   "StopId": "cb038446-bbad-5460-79f7-4b138024968b",
   "Code": "Stop- 001",
   "Name": "Lane market",
   "Fee": "600" 
  },
  {
   "StopId": "2502ce2a-900e-e686-79ea-33a2305abf91",
   "Code": "Stop-002",
   "Name": "City center",
   "Fee": "644" 
  }
 ],
  "StopsTiming" :
   [
       ....
   ] 
}

I want to fetch all embedded documents "StopDetails" only. I am trying to tweak below lines of codes but I am not able get what to write in $query "StopsDetails" in order to fetch only StopsDetails embedded document. Please help !!!

   $query = ['_id' => new MongoDB\BSON\ObjectID($this->id), 
            'StopsDetails' => ];

    try 
    {
        $cursor = $this->collection->find($query);
    } 
    catch (Exception $e) 
    {

    }
    return $cursor->toArray();

Solution

  • You need to use projection in the second parameter of the query

    $query = ['_id' => new MongoDB\BSON\ObjectID($this->id)]
    $projection = ['StopsDetails' => true]
    
    $cursor = $this->collection->find($query, $projection);
    

    which is similar to the javascript query

    db.collection.find({ '_id': ObjectId }, { 'StopDetails': 1 })