我遵循了mongoDB的结构:
bios
来自MongoVUE:
这是我的PHP代码片段:
$db = new Mongo('mongodb://fess:boo@1.2.3.4/bios');
// if i remove "bios" it asks default db name
$collection_bios2 = $db->bios2;
$cursor_bios2 = $collection_bios2->find(); // <- here I get error
// PHP Fatal error: Call to undefined method MongoDB::find()
...
$db->close();
为什么我收到此错误?
我看到了其他示例,似乎$collection_bios2
应该是集合。
由于
答案 0 :(得分:3)
你选择db吗?比如
$mongo = new Mongo();
// the following two lines are equivalent
$db = $mongo->selectDB("foo");
$db = $mongo->foo;
答案 1 :(得分:1)
发现问题。为了仅创建连接,我需要为admin创建用户/ pswd:
通过mongoDB CLI:
> use admin
> use bios
> db.createUser("fess", "boo");
实际上我只有bios
DB
否则会让我失误:
连接到MongoDB服务器时出错连接失败:1.2.3.4:27017:数据库'admin'上的用户名为'fess'的身份验证失败:auth失败
<强> PHP 强>
// here we create just client (for admin aka root)
$m = new MongoClient('mongodb://fess:boo@1.2.3.4');
// and switch to "bios"
$db = $m->selectDB("bios");
$list = $db->listCollections();
foreach ($list as $collection) {
Log::Debug(get_class() . " -> testMongoDB", "feederliteRC/U", array("Output" => "collection: $collection"));
}
//$db = new Mongo('mongodb://max:bagabu@172.20.0.23/bios');
//$collection_bios = $db->bios;
$collection_bios2 = $db->bios2;
<强>输出强>
"collection: bios.bios2"
答案 2 :(得分:0)
对我来说,如下所示。我使用了“mongodb / mongodb”和packagist的作曲家。 “作曲家需要mongodb / mongodb”。
require(__DIR__."/vendor/autoload.php");
use MongoDB\Client as MGDClient;
$collection = (new MGDClient(username:password@127.0.0.1:27017/db_name))->db_name->collection_name;
$cursor = $collection->find([],['limit'=>5]);
var_dump($cursor);