认证

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

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

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

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

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

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

如果链接中断,驱动会重新尝试链接并会自动重新认证。