直接访问PHP文件时,我没有从数据库返回任何结果,但下面的所有echo
检查都返回了预期的结果。
这是整个PHP文件。
<?php
$ext = new ReflectionExtension('mongo'); // see http://php.net/manual/en/reflectionextension.getversion.php
var_dump($ext->getVersion()); // returns string(5) "1.3.4"
echo extension_loaded("mongo") ? "loaded<br />" : "not loaded<br />"; // check if driver installed - returns "loaded"
$dbhost = '127.x.xx.x';
$dbname = 'mydb';
$m = new Mongo("mongodb://$dbhost"); // also tried 'MongoClient' rather than 'Mongo'
if ($m == true) {
echo "<br />connected to {$m}<br />"; // returns "connected to 127.x.xx.x:27017
}
$db = $m->$dbname;
$collection = $db->myCollection;
echo "<br />my collection is called {$collection}<br />"; // returns "my collection is called mydb.myCollection"
$query = $collection->find();
if ($query == true) {
echo "<br />the find method works"; // this is being returned
}
foreach($query as $result) { // nothing is happening here
var_dump($result);
}
?>
命令行查询:
db.myCollection.find();
返回预期结果(有一个文档)。
答案 0 :(得分:0)
您使用的是什么版本的PECL mongo lib?如果&gt; = 1.3.0(我们现在1.4.3稳定),则不推荐使用Mongo
类,而是鼓励您使用MongoClient
。
请参阅phpDoc。
答案 1 :(得分:0)
<强>解决方案强>
将上述代码调整为:
$dbhost = 'username:password@127.x.xx.x:27017/';
$dbname = 'yourdbname';
$m = new MongoClient("mongodb://$dbhost");
在我的情况下,我需要定义IP地址。