Mongodb Server Selection Timeout Error target machine refused connection


Connect to MongoDB db/collection using Python.


Target machine is local windows Mongodb. Running in Jupyter. This is a first attempt to get a connection via Python to a MongoDB. The MongoDB Compass is active and I created a localhost, authentication None new connection. The collection ‘db_analytics’ is created and visible. The code does reach ok with the “MongoDB Connection successfully” working. The code fails with timeout error on ‘collection.insert_one()’ function. What are some causes for target machine refusing connection? Is there any other approach to a python connection that I am missing here?

enter image description here

enter image description here

Python Code

import os
import datetime
import dotenv
import pymongo

mongo_database_name = 'db_analytics'
mongo_collection_name = 'analytics'

    db_client = pymongo.MongoClient(f"mongodb://")
    db = db_client[mongo_database_name]
    collection = db[mongo_collection_name]
    db = db.database
    print("MongoDB Connection successfully")
    print("Failed MongoDB connection")

analysis_item1 = {
        "topic":"Data Analytics",
        "Lat": 'Latitude',
        "Long": 'Longitude', 
analysis_item2 = {
        "topic":"Data Analytics",
        "Lat": 'Latitude',
        "Long": 'Longitude', 

a_test_rec1 = collection.insert_one(analysis_item1)
a_test_rec2 = collection.insert_one(analysis_item2)

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


ServerSelectionTimeoutError: [WinError 10061] No connection could be made because the target machine actively refused it, Timeout: 30s, Topology Description: <TopologyDescription id: 607bade837307b2e12ed0f7e, topology_type: Single, servers: [<ServerDescription ('', 27020) server_type: Unknown, rtt: None, error=AutoReconnect(' [WinError 10061] No connection could be made because the target machine actively refused it')>]>


Pymongo doesn’t make an “actual” database connection until you run an initial query (i.e. a find / insert etc.)

So you can have an incorrect connection string and it won’t raise an error when creating the MongoClient object. You can put whatever you like in the connection string it won’t raise an error (try it!)

db_client = pymongo.MongoClient("whatever you like")
print('Connected OK!')

In your case, as the commenter noted, your compass connection is on port 27017 and your pymongo connection is on port 27020. You need to correct the line to:

db_client = pymongo.MongoClient(f"mongodb://")

or, given 27017 is the default port, just:

db_client = pymongo.MongoClient(f"mongodb://")


Starting with version 3.0 the MongoClient constructor no longer blocks while connecting to the server or servers, and it no longer raises ConnectionFailure if they are unavailable, nor ConfigurationError if the user’s credentials are wrong. Instead, the constructor returns immediately and launches the connection process on background threads.