如何在php 7中连接到mongodb数据库

时间:2016-09-03 04:40:17

标签: php mongodb database

我使用的是mongodb 3.2和php 7 我已经安装了驱动程序及其工作.. 这是我的代码

<?php
$client = new MongoDB\Driver\Manager();
$db = $client->selectDatabase('inventory');
?>

如何连接数据库&#34;库存&#34; 出现的错误是

Fatal error: Uncaught Error: Call to undefined method MongoDB\Driver\Manager::selectDatabase() 

1 个答案:

答案 0 :(得分:2)

我不认为您想直接致电经理。更新的MongoDB扩展,取代了内置的PHP Mongo DB客户端;您需要满足以下要求才能使代码生效。下面的代码示例假设如下:

  1. 使用composer autoloader加载。
  2. 您可以从此处获得新的MongoDB驱动程序扩展程序:http://php.net/manual/en/set.mongodb.php
  3. 您从这里使用作曲家MongoDB客户端库:http://php.net/manual/en/mongodb.tutorial.library.php
  4. PHP&gt; = 5.6
  5. 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";
    }