Reputation: 81
I am using mongodb 3.2 and php 7 I have installed the driver and its working.. Here is my code
<?php
$client = new MongoDB\Driver\Manager();
$db = $client->selectDatabase('inventory');
?>
how to connect to database "inventory" the error that comes is
Fatal error: Uncaught Error: Call to undefined method MongoDB\Driver\Manager::selectDatabase()
Upvotes: 3
Views: 5181
Reputation: 4384
I don't think you want to call the Manager directly. The newer MongoDB extension that replaces the built-in PHP Mongo DB client; You need to have the following requirements for the code to work. The code example that follows assumes the following:
use MongoDB\Client as MongoDbClient;
// When auth is turned on, then pass in these as the second parameters to the client.
$options = [
'password' => '123456',
'username' => 'superUser',
];
try {
$mongoDbClient = new MongoDbClient('mongodb://localhost:27017');
} catch (Exception $error) {
echo $error->getMessage(); die(1);
}
// This will get or make (in case it does not exist) the inventory database
// and a collection beers in the Mongo DV server.
$collection = $mongoDbClient->inventory->beers;
$collection->insertOne( [ 'name' => 'Hinterland', 'brewery' => 'BrewDog' ] );
$result = $collection->find( [ 'name' => 'Hinterland', 'brewery' => 'BrewDog' ] );
foreach ($result as $entry) {
echo $entry['_id'], ': ', $entry['name'], "\n";
}
Upvotes: 2