Search code examples
phpmongodbmongodb-queryphp-mongodbmongodb-atlas

PHP MongoDB Driver on shared hosting doesnt connect to atlas


Connecting to the mongodb atlas free tier from a sharedhosting using mongodb driver 1.5.2 and trying to write a simple document gives the following error. What am I doing wrong?

$manager = new MongoDB\Driver\Manager("mongodb://admin:admin@test-shard-00-00-rbgc.mongodb.net:27017/db?ssl=false&replicaSet=test-shard-0&authSource=admin&serverSelectionTryOnce=false");

var_dump($manager);

$bulk = new MongoDB\Driver\BulkWrite;

$bulk->insert(['x' => 1]);
$manager->executeBulkWrite('db.collection', $bulk);

Fatal error: Uncaught MongoDB\Driver\Exception\ConnectionTimeoutException: No suitable servers found: serverselectiontimeoutms timed out: [connection closed calling ismaster on 'test-shard-00-00-waf4c.mongodb.net:27017'] in /Applications/AMPPS/www/mongodb/liveserver.php:63

When I var_dump the $manager I get:

object(MongoDB\Driver\Manager)#1 (2) { ["uri"]=> string(64) "admin:admin@test-shard-00-00-rbgc.mongodb.net:27017/" ["cluster"]=> array(0) { } }

I have also tried the following but the errors keeps being the same:

$manager = new MongoDB\Driver\Manager('mongodb://admin:admin@pirat-shard-00-00-vegbq.gcp.mongodb.net:27017/db?ssl=falseweak_cert_validation=false');

$bulk = new MongoDB\Driver\BulkWrite;


$bulk->insert(['x' => 1]);
$bulk->insert(['x' => 2]);
$bulk->insert(['x' => 3]);
$manager->executeBulkWrite('db.collection2', $bulk);

Solution

  • The connection string is wrong. There are 2 versions for new and legacy drivers, both versions are provided by atlas:

    enter image description here

    The 3.6+ version should be:

    mongodb+srv://admin:admin@test-shard-rbgc.mongodb.net:27017/db?retryWrites=true
    

    It's mongodb+srv:// and a single address of the shard with little parameters. It should work with mongodb-1.5. If not, try the legacy one:

    The 3.4- version should be (a single line):

    mongodb://admin:admin@test-shard-00-00-rbgc.mongodb.net:27017,
       test-shard-00-01-rbgc.mongodb.net:27017,
       test-shard-00-02-rbgc.mongodb.net:27017
       /db?ssl=true&replicaSet=Test-shard-0&authSource=admin&retryWrites=true
    

    It's mongodb://, list of all members of the replica set in the url, name of the replicaset in the parameter etc.

    Also, ensure your server's IP address is whitelisted in the atlas.