Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to test MongoDB connection in PHP?

Tags:

php

mongodb

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?

like image 995
darckcrystale Avatar asked May 15 '17 10:05

darckcrystale


People also ask

How do I know if my MongoDB database is connected?

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.

Can we connect MongoDB with PHP?

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.


1 Answers

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.

like image 53
darckcrystale Avatar answered Oct 19 '22 04:10

darckcrystale