0
votes

Okay, I've set up an account with MongoDB Atlas, and created a cluster. With the help of those details, I am now connected to the server using mongo shell. Imported a JSON file successfully, and I am able query and retrieve the data from collections after connecting to the cluster(from Mongo console only).

The problem is when I use the connection url inside my PHP file to fetch and display the data, I am unable to do so, every time it's giving me fatal error-

Fatal error: Uncaught MongoDB\Driver\Exception\AuthenticationException: Authentication failed. in E:\XAMPP\htdocs\mongoDB\MongoAutoLoad\mongodb\mongodb\src\Operation\Find.php:280 Stack trace: #0 E:\XAMPP\htdocs\mongoDB\MongoAutoLoad\mongodb\mongodb\src\Operation\Find.php(280): MongoDB\Driver\Server->executeQuery('test.bf', Object(MongoDB\Driver\Query), Object(MongoDB\Driver\ReadPreference))

1 E:\XAMPP\htdocs\mongoDB\MongoAutoLoad\mongodb\mongodb\src\Collection.php(527): MongoDB\Operation\Find->execute(Object(MongoDB\Driver\Server)) #2 E:\XAMPP\htdocs\mongoDB\bFreidan\testCluster.php(8): MongoDB\Collection->find() #3 {main} thrown in E:\XAMPP\htdocs\mongoDB\bFreidan\MongoAutoLoad\mongodb\mongodb\src\Operation\Find.php on line 280

Find.php is just the PHP library code for fetching and displaying collections data. What could be the problem here?

Please note that this code is working absolutely fine, if I am executing it in my local mongodb

Here's my PHP code -

<?PHP
require 'MongoAutoLoad/autoload.php'; // include Composer's autoloader
$client = new MongoDB\Client(
    'mongodb://<ClusterUsername>:<ClusterPassword>@cluster0-shard-00-00-91fmq.mongodb.net:27017,cluster0-shard-00-01-91fmq.mongodb.net:27017,cluster0-shard-00-02-91fmq.mongodb.net:27017/test?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin
');

$collection = $client->test->bf;
$result = $collection->find( [ 'name' => $name, 'brewery' => $brewery ] );

foreach ($result as $entry) {
    echo $entry['_id'], ': ', $entry['name'], "<br>"; //Print with ID
}
?>
1
In short you are able to connect to MongoDB Atlas from Mongo shell but not from Application, right?? - Mehraj Malik
Yes, From the application, which is hosted in xampp for now.. - Prashanth kumar

1 Answers

0
votes

There are two possible issues here.

First please ensure that your PHP driver is compatible with the MongoDB server version. Please see PHP driver compatibility table for more information.

You can check your MongoDB PHP driver version using below command :

php --ri mongodb | grep version

Another possibility is that you're sending an incorrect/unencoded password. If the password contains special characters (i.e. @ : or %), you should encode the password in the URI. See also MongoDB\Driver\Manager::__construct() and MongoDB\Client::__construct() for more information.