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.
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
Is there a way to test in PHP the connection to a MongoDB database?
Here, in the mongo shell, we can also check the currently active connections of the database server. The serverStatus returns a document that gives an overview of the current status of the database process.
You can add the driver to your application to work with MongoDB in PHP. The MongoDB PHP Driver consists of the two following components: The extension , which provides a low-level API and mainly serves to integrate libmongoc and libbson with PHP.
Ok, I found a way to test it!
<?php
$mongo = new MongoDB\Client('mongodb://my_server_does_not_exist_here:27017');
$dbs = $mongo->listDatabases();
If the connection fails, listDatabases
throws a MongoDB\Driver\Exception\ConnectionTimeoutException
. You just need to set a try/catch around the listDatabases
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With