简体   繁体   中英

How to solve Fatal error: Class 'MongoClient' not found?

I am using windows 10 64 bit, xampp 3.2.2, PHP 5.6.30, PHP Extension Build VC11, MongoDB server version: 3.4.3.

I am getting error like "Fatal error: Class 'MongoClient' not found in D:\\xampp\\htdocs\\test\\test1.php on line 4".

Here is the code I am using

CODE

<?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";
}

?>

I have added dll file in folder (D:\\xampp\\php\\ext) and added extension in php.ini (D:\\xampp\\php) "extension=php_mongodb.dll". But issue is not solved.

MongoDB (Mongo db is working)

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

MongoClient belongs to long deprecated Mongo extension . The new MongoDB extension uses Manager to connect to the database, eg

$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";
}

Or use any of higher level abstraction libraries. Eg https://github.com/mongodb/mongo-php-library provides interface similar to the legacy driver.

MongoDB\\Driver\\Manager is responsible for maintaining connections to MongoDB.

Connection

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

Listing databases

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

Reading All data

$query = new MongoDB\Driver\Query([]); 

$rows = $mng->executeQuery("database_name.collection_name", $query);

foreach ($rows as $row) {

    echo "$row->name\n";
}

Bulk Write(to perform two or more operations simultanously)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM