Search code examples
phpmongodbforeachmongodb-queryphp-mongodb

How to code MongoDB foreach Query in PHP


How to code MongoDB foreach Query in PHP ?

Now i have to code the same MONGODB QUERY in PHP with iterator_to_array, i don't know how to get this query to execute in PHP.

Now i stucked in this. i have given my data with some example.

USED MONGO QUERY:

db.getCollection('DRUM').find({'CODE': 'XXYYZZYY'}).forEach(
function(doc)
{
    print(doc.COLLECTION.DAY);
});

Actual DB RECORD:

{
   "CODE" : "XXYYZZYY",
   "COLLECTION" : {
      "DAY" : {
         "2017-06-05" : {
            "id" : 565455
         },
         "2017-06-15" : {
            "id" : 565445
         }
      },
      "MONTHLY" : {
         "2017-06-01" : {
            "id" : 564444
         },
         "2017-05-01" : {
            "id" : 565455
         }
      }
   },
   "success" : true
}

EXPECTED OUTPUT:

{
   "CODE" : "XXYYZZYY",
   "COLLECTION" : {
      "DAY" : {
         "2017-06-05" : {
            "id" : 565455
         },
         "2017-06-15" : {
            "id" : 565445
         }
      }
   },
   "success" : true
}

Solution

  • You can't directly execute same query from php. You have to first fetch the records from mongo and then iterate over that result.

    Here is my code for the same with PHP7 mongodb driver.

    //connection object
    $connection = new \MongoDB\Driver\Manager("mongodb://127.0.0.1:27017");
    
    $filter = ['CODE' => 'XXYYZZYY'];
    $projection['projection'] = ["COLLECTION.DAY" => 1,"CODE" => 1];
    
    $query = new \MongoDB\Driver\Query($filter,$projection);
    $cursor = $connection->executeQuery('DB_NAME.DRUM', $query);
    foreach($cursor as $key => $row) {
        print_r($row); //your expected output
    }