2013-05-27 19 views
1

我遵循的MongoDB的結構:PHP致命錯誤:調用未定義的方法的MongoDB :: find()方法時,試圖用收集

  • DB名稱:bios
  • 用戶: 「坦白」
  • 密碼: 「噓」
  • IP:1.2.3.4
  • 集合名稱:BIOS2

從MongoVUE:

enter image description here

這是我的PHP代碼片段:

$db = new Mongo('mongodb://fess:[email protected]/bios'); 

// if i remove "bios" it asks default db name 

$collection_bios2 = $db->bios2; 

$cursor_bios2 = $collection_bios2->find(); // <- here I get error 
// PHP Fatal error: Call to undefined method MongoDB::find() 

... 
$db->close(); 

爲什麼我得到這個錯誤?
我看到其他的例子,似乎$collection_bios2應該收集。

謝謝

回答

3

您是否選擇db?如

$mongo = new Mongo(); 
// the following two lines are equivalent 
$db = $mongo->selectDB("foo"); 
$db = $mongo->foo; 
1

發現問題。爲了只創建連接,第1關我需要管理員創建用戶/ PSWD:

通過MongoDB的CLI:

> use admin 
> use bios 
> db.createUser("fess", "boo"); 

其實我有用戶只爲bios DB

否則會寫信給我錯誤:

Error connecting to MongoDB server Failed to connect to: 1.2.3.4:27017: Authentication failed on database 'admin' with username 'fess': auth fails

PHP

 // here we create just client (for admin aka root) 
     $m = new MongoClient('mongodb://fess:[email protected]'); 

     // and switch to "bios" 
     $db = $m->selectDB("bios"); 

     $list = $db->listCollections(); 
     foreach ($list as $collection) { 
      Log::Debug(get_class() . " -> testMongoDB", "feederliteRC/U", array("Output" => "collection: $collection")); 

     } 

     //$db = new Mongo('mongodb://max:[email protected]/bios'); 

     //$collection_bios = $db->bios; 
     $collection_bios2 = $db->bios2; 

輸出

"collection: bios.bios2" 
0

對我來說,這是很好如下。我和packagist的作曲家一起使用了「mongodb/mongodb」。 「作曲家需要mongodb/mongodb」。

require(__DIR__."/vendor/autoload.php"); 
use MongoDB\Client as MGDClient; 

$collection = (new MGDClient(username:[email protected]:27017/db_name))->db_name->collection_name; 

$cursor = $collection->find([],['limit'=>5]); 

var_dump($cursor); 
相關問題