2

I am using laravel 5.5 and mongodb. I had successfully connected mongodb with my local system. But I am trying to connect with mongodb atlas cluster. I tried different ways but I need some detail information on this. Can anyone also explain what is the format of DNS?

I am following Connect laravel jenssegers to mongodb atlas cluster.

I copied my dsn from atlas cluster

This is my config inside connection :

'mongodb_conn' => [ 'driver' => 'mongodb', 'dsn'=>'mongodb+srv://username:password@hostname/test?retryWrites=true', 'database' => 'db_name',],

Thanks

Sundar Ban
  • 51
  • 1
  • 8

1 Answers1

2

With the DSN format you can specify all your parameters and configuration for connecting with Mongo with a single URL. This includes the cluster URL, replicas URL, authentication data, port and options. To get the DSN URL for your cluster at Mongo Atlas:

Click on the connect button on your cluster: connect

Select "Connect your application": application

From here if you choose I'm using driver 3.4 or earlier. You'll get a URL like this:

mongodb://<USER>:<PASSWORD>@shardname00.mongodb.net:27017,shardname01.mongodb.net:27017,shardname02.mongodb.net:27017/test?ssl=true&replicaSet=replicaName&authSource=admin&retryWrites=true

In this URL you just need to replace user and password and the rest you can leave as is.

If you choose I'm using driver 3.6 or later. You'll get a URL like this:

mongodb+srv://<USER>:<PASSWORD>@clusterName.mongodb.net/test?retryWrites=true

Notice the +srv at the beginning. This is important to let the driver know it's a SRV record.

If you don't have any restrictions to your environment you should prefer the latest option as this gives you more flexibility as you don't need to change your config if you add more replicas later.

Connecting from PHP you should add also add these parameters at the end of your DSN URL:

serverSelectionTryOnce=false&serverSelectionTimeoutMS=30000

More information about the parameters and connection string you can find at the Mongo Docs

Eduardo Lelis
  • 395
  • 2
  • 9