Martin Martin - 1 year ago 114
PHP Question

Cant connect to a mongodb database user with php

I've a running mongod with

on my server.

If I log to my admin user (from the admin database), no problem to fetch data.

$connection = new Mongo("mongodb://admin:adminpass@");

$db = $connection->selectDB( "mydb" );
$collection = $db->selectCollection( "user" );

but if I replace the first line by

$connection = new Mongo("mongodb://mydbadmin:dbadminpass@");

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 .....

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?


according to

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 .....

Answer Source

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:adminpass@");

notice the /mydb after the host-part, which lets the PHP-api connect to the desired database.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download