问题描述
我的服务器上运行的是auth=true
的mongod.
I've a running mongod with auth=true
on my server.
如果我从管理数据库登录到管理员用户,则获取数据没有问题.
If I log to my admin user (from the admin database), no problem to fetch data.
<?php
$connection = new Mongo("mongodb://admin:[email protected]");
$db = $connection->selectDB( "mydb" );
$collection = $db->selectCollection( "user" );
var_dump($collection->findOne());
?>
但是如果我将第一行替换为
but if I replace the first line by
$connection = new Mongo("mongodb://mydbadmin:[email protected]:27017");
它无法连接并出现错误:
It can not connect and get an error like :
Fatal error: Uncaught exception 'MongoConnectionException' with message 'Couldn't authenticate with database admin: username [mydbadmin]' in .....
所以问题是new Mongo()
尝试将我的用户连接到admin数据库而不是"mydb"数据库.如何选择要连接的数据库?
So the problem is new Mongo()
try to connect my user to the admin database instead of the "mydb" database. How can I choose the database I want to connect?
根据 http://php.net/manual/fr/mongo.construct进行. php
我尝试过了
according to http://php.net/manual/fr/mongo.construct.php
I tried this
$login = array("username" => "mydbadmin",
"password" => "dbadminpass",
"db" => "mydb",
"connect" => true
);
$connection = new Mongo("mongodb://localhost", $login);
但是
Couldn't authenticate with database mydb: username [mydbadmin]' in .....
推荐答案
好吧,如果您未在构造函数中指定db,则默认情况下它将使用admin
数据库(如 Mongo::__construct
-参考).请尝试以下操作:
Well if you don't specify a db in the constructor, it uses the admin
database by default (as documented in the Mongo::__construct
-reference). Try the following:
$connection = new Mongo("mongodb://admin:[email protected]/mydb");
在主机部分之后注意/mydb
,它使PHP-api连接到所需的数据库.
notice the /mydb
after the host-part, which lets the PHP-api connect to the desired database.
这篇关于无法使用php连接到mongodb数据库用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!