Vivek Nuna
Vivek Nuna

Reputation: 1

MongoServerSelectionError: connection <monitor> to <MyIP> closed

I have started learning MongoDB, I am just trying to connect to the database using MongoDB Shell. I am using the below command.

mongosh "mongodb+srv://cluster0.12345.mongodb.net/myFirstDatabase" --username viveknuna

I have added my current IP Address to IP Access List. But getting this error.

MongoServerSelectionError: connection to closed

I have referred to this question and added 0.0.0.0/0 (Allow access from AnyWhere) in the IP Access List. and it works as expected. But this is a security risk, Is there any way without allowing all IPs.

FYI: I am inside Virtual Machine and running this command also from VM.

Upvotes: 3

Views: 10524

Answers (3)

Charles Arko-Clayman
Charles Arko-Clayman

Reputation: 336

This happens when your ip address on the remote mongoDb is not the same as the public ip address of your computer. Simply go to network access on atlas and add your public ip address. Also, if your ip address is the same as that on the remote mongoDb then probably the connection closed after some period(default is 6hours).Thus when adding a your ip, unsure you toggle and set the duration for the connection (max is a week)

Upvotes: 1

jospert
jospert

Reputation: 144

in my case when i got these error MongoServerSelectionError: connection <monitor> to 16.163.195.9:27017 closed

I actualy put the wrong ip address i put my private ip; thats why.

i fixed it by changing the ip address in the IP List from WAN IP to my Public IP address thats how i fixed it, just search what is my ip, in you favorite seach Engine and it will show you your public ip in the result.

Upvotes: 4

utkarsh-k
utkarsh-k

Reputation: 983

For me this error was occurring because my connection string was wrong.To be very specific - I copied the sample connection string from a course I was learning and just replaced the username and password with my credentials. So, the credentials were right but not the rest of the connection string.

Just for the sake of understanding. Please see below :

 mongodb+srv://myusername:[email protected]/?retryWrites=true&w=majority" 

myusername and mypassword are correct i.e belongs to my cluster in MongoDB atlas account, but the rest of the string is wrong as I copied it from somewhere instead of copying it from my own MongoDB atlas account.

So please make sure to double check if your entire connection string is correct.

Upvotes: 1

Related Questions