Question

PHP connection to MongoDB cluster

Hello, I’ve difficulties with connection to MongoDB cluster on DigitalOcean by PHP. As we know, we have to use SSL, but I don’t know how. My code is as follows:

<?php
require_once __DIR__ . "/vendor/autoload.php";
$db = new MongoDB\Client('mongodb://[myapp].mongo.ondigitalocean.com', array(
    'username' => 'doadmin',
    'password' => '[password]',
    'db'       => '[database]',
	'authSource' => 'admin',
	'replicaSet' => '[replica]',
	'tls' => 'true',
	'tlsCAFile' => '/usr/share/ca-certificates/app/ca-certificate.pem'
));

$db = $conn->[database];
$collection = $db->[collection];
?>

I am getting an error: ‘Uncaught MongoDB\Driver\Exception\ConnectionTimeoutException: No suitable servers found’.

Do you know how to connect properly in this case? Thank you in advance.

Subscribe
Share

Submit an answer
You can type!ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Hi there @MichalGiza,

I have just tested this with the code snippet that you’ve provided and it all worked as expected.

As you are getting a connection timeout exception, this is most likely caused by one of the following:

  • Port 27017 is closed for outgoing connections on your server, if this is the case you need to make sure that it is open.

  • You have used the Trusted sources functionality and locked down your database cluster for a specific IP only. If this is the case you would need to allow your server IP as well so that it could connect to the database cluster.

You could test the connectivity after that with the mongo command-line tool to make sure that you actually can connect to the cluster:

mongo "mongodb+srv://doadmin:password@cluster_name.mongo.ondigitalocean.com/admin?authSource=admin&replicaSet=replica_set_name" --tls --tlsCAFile <replace-with-path-to-CA-cert>

Let me know how it goes! Regards, Bobby