鍍金池/ 問答/PHP  數(shù)據(jù)庫/ php 使用 uri 方式連接 mongodb,無權限正常連接,有權限就失敗。

php 使用 uri 方式連接 mongodb,無權限正常連接,有權限就失敗。

在無權限認證的情況下去通過php連接mongodb可以連接,而且數(shù)據(jù)也可以讀取出來。

$con = new MongoClient();
//這樣之后操作讀取都可以。

但是添加上用戶權限認證之后,就一直提示fatal error, authentication failed等,用戶名密碼正確沒有權限。

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

這句一直連接錯誤。
但是通過客戶端的方式來連接就可以

> mongo phptest -u test -p test123

這樣就可以正常的讀寫操作。

回答
編輯回答
淡墨

根據(jù) 官方文檔中對 mongo uri 的介紹, uri 后面指定的那個 database, 是用來指定授權數(shù)據(jù)庫的, 而不是用來指定連接成功后選擇的數(shù)據(jù)庫的.

/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.

之所以需要指定授權數(shù)據(jù)庫, 是因為授權數(shù)據(jù)庫并不總是會被起名為 admin, 這個名字只是大多數(shù)人都會起的名字, 也是 mongo 默認會連接的授權數(shù)據(jù)庫名. 你真把授權數(shù)據(jù)庫起名成 test 也是可以的, 那連接時就需要指定授權庫為 test : mongo://user:pass@localhost:27017/test .

回到你的問題, 你的授權庫應該不叫 phptest 吧. 把這個數(shù)據(jù)庫名去掉, 應該就可以連接成功. 連接成功后, 再用 MongoClient 選擇庫就是了. php 的 mongo 語法還是超級簡單的:

$mongo_client->phptest
2017年5月9日 18:51