Connect to Atlas with Pymongo

Having an issue connecting to Altas Cluster, I have whitelisted ip To ensure I was able to connect to the db I printed the collection name to console. But when I try and insert a document into the collection, I get this error.

pymongo.errors.ServerSelectionTimeoutError: [Errno 8] nodename nor servname provided, or not known

I have tried
collection_name.insert_one(json_data) same error.

# Python code to illustrate

inserting data in MongoDB

from pymongo import MongoClient

conn = MongoClient()
print(“Connected successfully!!!”)
print(“Could not connect to MongoDB”)


db = conn.my_database

Created or Switched to collection names: my_gfg_collection

collection = db.my_collection

emp_rec1 = {
emp_rec2 = {

Insert Data

rec_id1 = collection.insert_one(emp_rec1)
rec_id2 = collection.insert_one(emp_rec2)

print(“Data inserted with record ids”,rec_id1," ",rec_id2)

Printing the data inserted

cursor = collection.find()
for record in cursor:

Your are sure you do not have a typo in the following name

No you do not have a typo because I could connect to your server with the shell. So please setup some password.

I am not fluent in python but would MongoClient() need a parameter?

@steevej-1495 I amused there so no typo in the connection string, since I am able to successfully print the collection name to console, I could be wrong I do not know. I have tried the below


Both produce the same result

Yes, oops I am passing this in to mongoclient(“mongodb://”)

@steevej-1495 How did you connect to my database through the shell, could you post that because I am getting something different

I am able to connect with compass, I am thinking it might be a configuration issue with atlas, I created a user on startup and thought this was good, I dont know. Any ideas???

Sorry for the delay. I was out for lunch.

I connected with the shell with the following

mongo "mongodb+srv://" 

But I am not authenticated, which is a good thing.

MongoDB Enterprise MongaStreamListener-shard-0:PRIMARY> show dbs
2020-02-27T21:21:01.360-0500 E QUERY    [js] Error: listDatabases failed:{
	"operationTime" : Timestamp(1582857005, 1),
	"ok" : 0,
	"errmsg" : "command listDatabases requires authentication",
	"code" : 13,
	"codeName" : "Unauthorized",
	"$clusterTime" : {
		"clusterTime" : Timestamp(1582857005, 1),
		"signature" : {
			"hash" : BinData(0,"V5+rKj/GIWypHCNefz39V4zcsio="),
			"keyId" : NumberLong("6797186728361721858")
} :

Like @steevej-1495 is hinting, fix your connection string and you’re good to go:


Replace username and password