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.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
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
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.