2015-11-06 14 views
0

我正在使用php MongoClient()來登錄(auth = true),以使用Php的mongodb「test」。 現在我想切換分貝到「test1」使用PHP沒有身份驗證。 它適用於mongo shell命令 - 「use test1」 當我嘗試使用connection-> selectdb(「test1」)在php中執行相同的操作時,它會嘗試在「test1」db上驗證同一用戶並失敗。在PHP中沒有身份驗證的開關db mongodb

有沒有辦法使用Php Mongoclient()切換db?

上mongoshell下面的代碼將在測試和運行的MapReduce上test1.orders通過存儲test.SampleGroupby結果驗證USER1

mongo --host XXXX -u user1 -p XXXX --authenticationDatabase test 
use test1; /*I don't need to authenticate user1 on test1 (test.user1 already has read/write permission on test1) */ 
db.orders.mapReduce(mapf, redf, {"out": {reduce: "SampleGroupby", db: "test"}, finalize: finf }) 

現在同樣我想用PHP來實現 -

$Connection = MongoClient("mongodb://XXXX:XXXX", array("username" => user1, "password" => XXXX, "db" => test)); 
$Connection->test1->command(array( /*Here it tries to re authenticate user1 on test1 and fails */ 
"mapreduce" => orders, 
"map" => $map, 
"reduce" => $reduce, 
"out" => array("reduce" => SampleGroupby , "db" => test), 
"finalize" => $finalize 
)); 

回答

0

MongoClient是PHP類用於連接到MongoDB主機與連接字符串作爲參數。 連接字符串封裝用戶名,密碼和Mongodb主機。

如果MongoDB的被配置爲能夠驗證那麼只有用戶名和密碼被要求在連接字符串

EG。 的mongodb://用戶名:密碼@主機:端口

MongoClient將返回數據庫連接對象。

使用數據庫連接對象我們切換到特定的數據庫使用selectDB()方法。

例如,

$conn = new MongoClient('mongodb://username:[email protected]:port'); 
$db = $conn->selectDB("dbname"); 

如果啓用身份驗證,然後會有每個數據庫單獨的用戶。

因此,對於切換到另一個數據庫那麼我們就需要使用MongoClient與連接字符串作爲參數,使用返回的連接對象

沒有認證來定義一個新的連接對象,然後調用selectDB()方法使我們只是需要調用與數據庫名稱作爲參數的selectDB()方法

+0

感謝您的迴應。我明白了這一點,但問題在於,我無法獲得使用mongo shell的相同結果。以確切的方案更新問題。 –