Sarath TS
Sarath TS

Reputation: 2462

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

Upvotes: 0

Views: 9156

Answers (2)

ashish bansal
ashish bansal

Reputation: 411

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

Upvotes: 1

Alex Blex
Alex Blex

Reputation: 37048

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

$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. E.g. https://github.com/mongodb/mongo-php-library provides interface similar to the legacy driver.

Upvotes: 2

Related Questions