1

I have followed structure of mongoDB:

  • DB name: bios
  • user: "fess"
  • password: "boo"
  • IP: 1.2.3.4
  • collection name: bios2

From MongoVUE:

enter image description here

This is my snippets of PHP code:

$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();

Why I get this error?
I saw other examples and seems that $collection_bios2 should be collection.

Thanks

3 Answers 3

3

Do you select db? such as

$mongo = new Mongo();
// the following two lines are equivalent
$db = $mongo->selectDB("foo");
$db = $mongo->foo;
Sign up to request clarification or add additional context in comments.

Comments

1

Found the problem. In order to create connection only, 1st off I need create user/pswd for admin:

Through mongoDB CLI:

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

Actually I had user only for bios DB

Otherwise it will drop me error:

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;

Output

 "collection: bios.bios2"

Comments

0

For me, it is fine as below. I used "mongodb/mongodb" with composer from packagist. "composer require 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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.