Is there a way to test MongoDB connection in PHP?

Viewed 10359

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

I do:

<?php
$configuration = parse_ini_file("../configs/database.ini");
$mongo = new MongoDB\Client($configuration['resources.mongo.dsn']);
$db = $mongo->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://127.0.0.1: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?

3 Answers

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(self::$client instanceof Client){
                self::$client->listDatabases();
                return self::$client;
            } else {
                throw new \MongoDB\Driver\Exception\ConnectionTimeoutException("There is no connection yet");
            }

        } catch (\MongoDB\Driver\Exception\ConnectionTimeoutException $connectionTimeoutException){
            return self::newInstance();
        }
    }

    /**
     * @return string
     * creates a connection string based on the static properties available which this trait is used
     */
    private static function getMongoDbConnectionUri():string
    {
        return 'mongodb://' . self::$user . ':' . self::$pass . '@' . self::$host . ':' . self::$port . '/?authMechanism=' . self::$authMechanism . '&authSource=' . self::$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 {
            self::$client = new Client(self::getMongoDbConnectionUri());
            return self::$client;
        } catch (\MongoDB\Driver\Exception\ConnectionTimeoutException $connectionTimeoutException){
            throw $connectionTimeoutException;
        }
    }
}

For a Mysql like handling you can try this :

$client = new MongoDB\Client('mongodb://my_server_does_not_exist_here:27017');  

try{ 
    $dbs = $client->listDatabases(); 
    echo '<pre>';
    print_r($dbs);
    echo '</pre>';
    // Or Nothing if you just wanna check for errors 
}
catch(Exception $e){
    echo "Unable to connect to Database at the moment ! ";
    exit();
}

Related