pymongo function cannot connect to MongoDB Atlas

I am trying to use pymongo’s insert_one function to update my collection in the cloud. My code is able to find the database and collection, but when trying to insert a document into it I get the following error:

pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [WinError 10061] No connection could be made because the target machine actively refused it (configured timeouts: socketTimeoutMS: 20000.0ms, connectTimeoutMS: 20000.0ms), Timeout: 30s, Topology Description: <TopologyDescription id: 663ccd7a7222d218d94c6a37, topology_type: Unknown, servers: [<ServerDescription ('localhost', 27017) server_type: Unknown, 
rtt: None, error=AutoReconnect('localhost:27017: [WinError 10061] No connection could be made because the target machine actively refused it (configured timeouts: socketTimeoutMS: 20000.0ms, connectTimeoutMS: 20000.0ms)')>]>

I have checked the whitelisted IP’s and my address is in there, anyone else have any ideas?

Hey @Musa_Karim - welcome to the MongoDB community forums!

PyMongo is a really lazy driver, so it won’t connect to the database cluster until it absolutely has to. This means the following things don’t do anything on the network:

  • Creating a MongoClient
  • Getting a database
  • Getting a collection
  • Running find or aggregate :scream: (these return cursors, which are empty until you start to use them)

The following things do connect to the cluster and do stuff:

  • Running an insert or update
  • Running find_one
  • Looping through the results of a find or aggregate call.

So … what this means is that your code isn’t able to find the database and collection - it’s not even trying! This trips a lot of people up.

The error message states that your MongoClient is trying to connect to “localhost:27017”, which is the default if no connection string is provided. This means that you could be calling MongoClient() with no arguments, or what I suspect you’re doing is calling MongoClient(MDB_URI) where MDB_URI is None for some reason.

I hope this helps!

Mark