Mongodb Server Selection Timeout Error target machine refused connection

Purpose:

Connect to MongoDB db/collection using Python.

Issue:

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'

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

analysis_item1 = {
        "topic":"Data Analytics",
        "rank":2,
        "Lat": 'Latitude',
        "Long": 'Longitude', 
        "Province/State":"Germany"
        }
analysis_item2 = {
        "topic":"Data Analytics",
        "rank":5,
        "Lat": 'Latitude',
        "Long": 'Longitude', 
        "Province/State":"Africa"
        }

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

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

Error

ServerSelectionTimeoutError: 127.0.0.1:27020: [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 ('127.0.0.1', 27020) server_type: Unknown, rtt: None, error=AutoReconnect('127.0.0.1:27020: [WinError 10061] No connection could be made because the target machine actively refused it')>]>

Answer

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://127.0.0.1:27017/db_analytics")

or, given 27017 is the default port, just:

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

Source: https://pymongo.readthedocs.io/en/stable/api/pymongo/mongo_client.html#pymongo.mongo_client.MongoClient

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.