Authentication

If MongoDB is started with the --auth or --keyFile options, you must authenticate before you can do any operations with the driver. You may authenticate a connection by specifying the username and password in either the connection URI or the "username" and "password" options for MongoClient::__construct().

Example #1 Authenticating against the "admin" database

<?php
// Specifying the username and password in the connection URI (preferred)
$m = new MongoClient("mongodb://${username}:${password}@localhost");

// Specifying the username and password via the options array (alternative)
$m = new MongoClient("mongodb://localhost", array("username" => $username"password" => $password));
?>

By default, the driver will authenticate against the admin database. You may authenticate against a different database by specifying it in either the connection URI or the "db" option for MongoClient::__construct().

Example #2 Authenticating against normal databases

<?php
// Specifying the authentication database in the connection URI (preferred)
$m = new MongoClient("mongodb://${username}:${password}@localhost/myDatabase");

// Specifying the authentication database via the options array (alternative)
$m = new MongoClient("mongodb://${username}:${password}@localhost", array("db" => "myDatabase"));
?>

If your connection is dropped, the driver will automatically attempt to reconnect and reauthenticate you.

Коментарии

How does this work for connections to replication sets?

Does the connection string become:
"mongodb://user:password@server1:27017,server2:27017,server3:27017"
2015-01-05 18:11:00
http://php5.kiev.ua/manual/ru/mongo.connecting.auth.html
For connecting to a replica set with authentication it is possible to use a connection string like the following (substitute the port numbers, replica set name and DB with your own)

$m = new MongoClient("mongodb://${username}:${password}@localhost:27037,mongodb://${username}:${password}@localhost:27038", 
array("replicaSet" => "test"_replica, "db" => "mytestdb"));

The second member string "mongodb://${username}:${password}@localhost:27038" does not need the username and password - however, if the connection to the first member fails I have not tested to see if the username and password persist to the second member.
2015-05-25 19:18:33
http://php5.kiev.ua/manual/ru/mongo.connecting.auth.html

    Поддержать сайт на родительском проекте КГБ