Martin Martin - 4 months ago 27
PHP Question

Cant connect to a mongodb database user with php

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

$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:dbadminpass@127.0.0.1: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 .....


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?

EDIT :

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);


but

Couldn't authenticate with database mydb: username [mydbadmin]' in .....

Answer

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@127.0.0.1/mydb");

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