php 使用 uri 方式连接 mongodb,无权限正常连接,有权限就失败。

在无权限认证的情况下去通过php连接mongodb可以连接,而且数据也可以读取出来。

$con = new MongoClient();
//这样之后操作读取都可以。

但是添加上用户权限认证之后,就一直提示fatal error, authentication failed等,用户名密码正确没有权限。

$con = new MongoClient('mongodb://test:test123@localhost:27017/phptest');

这句一直连接错误。
但是通过客户端的方式来连接就可以

> mongo phptest -u test -p test123

这样就可以正常的读写操作。

阅读 4.7k
1 个回答

根据 官方文档中对 mongo uri 的介绍, uri 后面指定的那个 database, 是用来指定授权数据库的, 而不是用来指定连接成功后选择的数据库的.

/database : Optional. The name of the database to authenticate if the connection string includes authentication credentials in the form of username:password@. If /database is not specified and the connection string includes credentials, the driver will authenticate to the admin database.

之所以需要指定授权数据库, 是因为授权数据库并不总是会被起名为 admin, 这个名字只是大多数人都会起的名字, 也是 mongo 默认会连接的授权数据库名. 你真把授权数据库起名成 test 也是可以的, 那连接时就需要指定授权库为 test : mongo://user:pass@localhost:27017/test .

回到你的问题, 你的授权库应该不叫 phptest 吧. 把这个数据库名去掉, 应该就可以连接成功. 连接成功后, 再用 MongoClient 选择库就是了. php 的 mongo 语法还是超级简单的:

$mongo_client->phptest
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题