如何在PHP中编写MongoDB foreach查询代码 [英] How to code MongoDB foreach Query in PHP

查看:133
本文介绍了如何在PHP中编写MongoDB foreach查询代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在PHP中编写MongoDB foreach查询代码?

How to code MongoDB foreach Query in PHP ?

现在,我必须使用 iterator_to_array 在PHP中编码相同的 MONGODB QUERY ,我不知道如何在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.

使用过的蒙古查询:

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

实际数据库记录:

{
   "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
}

期望的输出:

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

推荐答案

您不能直接从php执行相同的查询.您必须首先从mongo中获取记录,然后遍历该结果.

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

这是我与PHP7 mongodb驱动程序相同的代码.

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
}

这篇关于如何在PHP中编写MongoDB foreach查询代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆