Jaffer Wilson
Jaffer Wilson

Reputation: 7273

Php and Mongodb not getting connected

I have tried the following example in order to display the collection count. Here is what I did:

<?php
 $connection = new MongoDB\Driver\Manager(Mongo URI);
//echo phpinfo();
$collection = new MongoDB\Collection($connection, "new", "items");
$initialCollectionCount = $collection->count();
echo $initialCollectionCount;
?>

I am getting the following error:

Fatal error: Uncaught Error: Class 'MongoDB\Collection' not found in C:\xampp\htdocs\test\test.php:4 Stack trace: #0 {main} thrown in C:\xampp\htdocs\test\test.php on line 4

What I did till now:
1) Downloaded the latest MongoDB drivers from the Pecl website for PHP 7.1.
2) added the DLL file to ext folder and edited the php.ini file.
3) Written code for the php and mongo Connection.

Kindly suggest me what I need to do to make my code run. Please note that I have added the System variable as PHP folder. There is nothing that I have not done till now.

Please suggest me the right track so my code get implemented.

Upvotes: 0

Views: 962

Answers (1)

Satish Saini
Satish Saini

Reputation: 2968

You can try retrieving the data using MongoDB\Driver\Query class of the extension.

// Manager Class / Connection
$connection = new MongoDB\Driver\Manager(Mongo URI);

// Query Class like this. Add your conditions here if there may be any
$query = new MongoDB\Driver\Query(array('id' => 1));

// Output of the executeQuery will be object of MongoDB\Driver\Cursor class
$cursor = $connection->executeQuery('new.items', $query);

// Convert cursor to Array and print result
print_r($cursor->toArray());

And then you can count the elements of output array.

This code runs fine when you are using latest MongoDB extension of PHP, MongoDB\Driver\Manager is the main entry point to the extension.

Answer to your comment: I didn't see a class to list all the collections. Alternatively, try using Mongo client until we get more support on MongoDB\Driver\Manager

Here is a sample code to list all collections from your database:

<?php

$m = new MongoClient();
$db = $m->selectDB("new");
$collections = $db->listCollections();

foreach ($collections as $collection) {
    echo "amount of documents in $collection: ";
    echo $collection->count(), "\n";
}

?>

The class MongoClient is part of the legacy PECL package mongo but not anymore of the up-to-date mogodb package.

This package has been superseded, but is still maintained for bugs and security fixes.

Upvotes: 1

Related Questions