How to code MongoDB foreach Query in PHP

这一生的挚爱 提交于 2019-12-10 11:40:00

问题


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
}

回答1:


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
}


来源:https://stackoverflow.com/questions/44896477/how-to-code-mongodb-foreach-query-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!