PHP 8.0.0 Beta 4 available for testing


如果 MongoDB 服务器启动时使用了 --auth--keyFile 参数,你就必须在进行任何操作前进行认证。 你可以在连接时进行认证。方法是在链接字符串中指定用户名密码,或者在 MongoClient::__construct() 构造函数中指定 "username""password"

Example #1 针对“admin”数据库的认证

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

默认状态下,驱动会针对 admin 数据库进行认证。认证也可以对其他数据库进行。方法是在连接字符串中指定数据库名,或者 MongoClient::__construct() 构造函数中指定 "db"

Example #2 针对一般数据库的认证

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


add a note add a note

User Contributed Notes 2 notes

dan at kayakaddict dot co dot uk
5 years ago
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.
davida at quickplay dot com
5 years ago
How does this work for connections to replication sets?

Does the connection string become:
To Top