Title: Is there a way to test MongoDB connection in PHP?
Tags: php;mongodb
Question: Context
I have a configuration file in which I precise the MongoDB connection string. I want to test my MongoDB connection, to precise to the devs using my code that their configuration is bad if it's the case.
I use the MongoDB driver.
I did not find anything about tests of the Mongo connection.
Problem
<?php
$configuration = parse_ini_file("../configs/database.ini");
$mongo = new MongoDB\Client($configuration['resources.mongo.dsn']);
$db = $mongo-&gt;stats;
But the only errors thrown are those about bad format of the MongoDB connection string. For example:
with test_bad_string, a MongoDB\Driver\Exception\InvalidArgumentException is thrown
with mongodb://151.154.11.224:270 (default port for my MongoDB is 27017), I don't see any errors
Question
Is there a way to test in PHP the connection to a MongoDB database?
Comment: Can you share more details, like which configuration would be seen as "faulty" and which as "correct"?

Here is the accepted answer: Ok, I found a way to test it!
<?php
$mongo = new MongoDB\Client('mongodb://my_server_does_not_exist_here:27017');
$dbs = $mongo-&gt;listDatabases();
If the connection fails, listDatabases throws a MongoDB\Driver\Exception\ConnectionTimeoutException. You just need to set a try/catch around the listDatabases.

Here is another answer: For a Mysql like handling you can try this :
$client = new MongoDB\Client('mongodb://my_server_does_not_exist_here:27017');
$dbs = $client-&gt;listDatabases();
echo '<pre&gt;';
print_r($dbs);
echo '</pre&gt;';
// Or Nothing if you just wanna check for errors
catch(Exception $e){
echo "Unable to connect to Database at the moment ! ";
exit();

Here is another answer: Hi I was checking out the answer above and wanted to share with people the simple singleton implementation for this as I am using it. Just use it in any class with the variables set up and it will turn the class into a singleton mongo db connection.
use MongoDB\Client; // Used extension
trait MongoDbClient
private static ?\MongoDB\Client $client = null;
/**
* @return Client
* the single function able to get the connection from, will check if the connection is alive and will route to the new instance factory method
*/
public static function getInstance(){
try {
if(sel75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0$client instanceof Client){
sel75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0$client-&gt;listDatabases();
return sel75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0$client;
} else {
throw new \MongoDB\Driver\Exception\ConnectionTimeoutException(&quot;There is no connection yet&quot;);
}
} catch (\MongoDB\Driver\Exception\ConnectionTimeoutException $connectionTimeoutException){
return sel75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0newInstance();
}
/**
* @return string
* creates a connection string based on the static properties available which this trait is used
*/
private static function getMongoDbConnectionUri():string
return 'mongodb://' . sel75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0$user . ':' . sel75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0$pass . '@' . sel75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0$host . ':' . sel75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0$port . '/?authMechanism=' . sel75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0$authMechanism . '&amp;authSource=' . sel75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0$authSource;
/**
* @return Client
* sets and returns a new client but throws a exception if a new connection timeout occurs
*/
private static function newInstance(): Client
try {
sel75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0$client = new Client(sel75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0getMongoDbConnectionUri());
return sel75b5:f2c1:f5d7:b954:8dc3:cee9:baf:a8c0$client;
} catch (\MongoDB\Driver\Exception\ConnectionTimeoutException $connectionTimeoutException){
throw $connectionTimeoutException;
}

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 3, 'CommentCount': 1, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2017:00:05/15/17', 'FavoriteCount': 1.0, 'PostTypeId': 1, 'Tags': '<php><mongodb>', 'Title': 'Is there a way to test MongoDB connection in PHP?', 'ViewCount': 10359, 'id': 43977509, 'user_AboutMe': "<p>I'm a queer pirate from outter space, looking for answers on the internet when I struggle on my dev.</p>\n\n<p>After several years using Q&amp;A in StackOverflow, I created an account to post my own questions and begin to give answers :D</p>\n", 'user_AccountId': 4166895.0, 'user_DisplayName': 'darckcrystale', 'user_Reputation': 1382.0, 'user_Views': 105.0, 'user_id': 3415679.0}}