【问题标题】:How to solve Fatal error: Class 'MongoClient' not found?如何解决致命错误:找不到类“MongoClient”?
【发布时间】:2017-09-02 10:04:21
【问题描述】:

我使用的是 windows 10 64 位、xampp 3.2.2、PHP 5.6.30、PHP Extension Build VC11、MongoDB 服务器版本:3.4.3。

我收到类似“致命错误:第 4 行的 D:\xampp\htdocs\test\test1.php 中未找到类 'MongoClient'”的错误。

这是我正在使用的代码

代码

<?php

// connect
$m = new MongoClient();

// select a database
$db = $m->cabin;

// select a collection (analogous to a relational database's table)
$collection = $db->user;

// find everything in the collection
$cursor = $collection->find();

// iterate through the results
foreach ($cursor as $document) {
    echo $document["title"] . "\n";
}

?>

我在文件夹(D:\xampp\php\ext) 中添加了 dll 文件,并在 php.ini (D:\xampp\php) "extension=php_mongodb.dll" 中添加了扩展名。但是问题没有解决。

MongoDB(Mongo db 正在运行)

user@DESKTOP-JCDJQ65 MINGW64 /d
$ mongo
MongoDB shell version v3.4.3
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.3
use cabin
switched to db cabin
show tables
bmessages
booking
cabins
club
country
customer
email
facilities
land
mschool
region
role
rooms
settings
tempuser
tour
user
userold
visit

【问题讨论】:

    标签: php mongodb


    【解决方案1】:

    MongoClient 属于早已弃用的Mongo extension。新的MongoDB extension 使用Manager 连接数据库,例如

    $m = new MongoDB\Driver\Manager("mongodb://localhost:27017");
    $cursor = $manager->executeQuery("cabin.user", new MongoDB\Driver\Query([]));
    foreach ($cursor as $document) {
        echo $document["title"] . "\n";
    }
    

    或者使用任何更高级别的抽象库。例如。 https://github.com/mongodb/mongo-php-library 提供类似于旧版驱动程序的接口。

    【讨论】:

      【解决方案2】:

      MongoDB\Driver\Manager 负责维护与 MongoDB 的连接。

      连接

      $mng = new MongoDB\Driver\Manager("mongodb://localhost:27017");
      

      列出数据库

      $listdatabases = new MongoDB\Driver\Command(["listDatabases" => 1]);
      $res = $mng->executeCommand("admin", $listdatabases);
      

      读取所有数据

      $query = new MongoDB\Driver\Query([]); 
      
      $rows = $mng->executeQuery("database_name.collection_name", $query);
      
      foreach ($rows as $row) {
      
          echo "$row->name\n";
      }
      

      批量写入(同时执行两个或多个操作)

      $bulk = new MongoDB\Driver\BulkWrite;
      
      $doc = ['_id' => new MongoDB\BSON\ObjectID, 'name' => 'Toyota', 'price' => 26700];
      $bulk->insert($doc);
      $bulk->update(['name' => 'Audi'], ['$set' => ['price' => 52000]]);
      $bulk->delete(['name' => 'Hummer']);
      
      $mng->executeBulkWrite('testdb.cars', $bulk);
      

      【讨论】:

        猜你喜欢
        • 2015-06-16
        • 2015-04-04
        • 1970-01-01
        • 2010-10-14
        • 1970-01-01
        • 2018-05-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多