ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connection refused, Timeout: 30s

Hello, everyone. I just started learning about MongoDB.
I have a question about accessing the data in MongoDB Compass via Python.
I have studies the document: Quickstart: Azure Cosmos DB for MongoDB for Python with MongoDB driver.
I stored the data in MongoDB Compass.
This data consist of

{'Sentence': "Cameron Baker", 'Embedding': [0.55, 0.89, 0.44]}

After that, I want to accessing the data in MongoDB Compass via Python.
I have studies the document: Using vector search on embeddings in Azure Cosmos DB for MongoDB vCore
I write the code for query vector as follow:

import os
import sys
import pymongo
from random import randint
from dotenv import load_dotenv

Authenticate the client

load_dotenv()

CONNECTION_STRING_ = os.environ.get("CONNECTION_STRING")
# Connection String format: ?tls=true&authMechanism=SCRAM-SHA-256&retrywrites=true&maxIdleTimeMS=120000"

DB_NAME = "documentsearch"
COLLECTION_NAME = "Test"

Connect to Azure Cosmos DB’s API for MongoDB

client = pymongo.MongoClient(CONNECTION_STRING_)

Query documents

db = client[DB_NAME]
collection = db[COLLECTION_NAME]
query_vector = [0.52, 0.28, 0.12]  
  
pipeline = [  
    {  
        "$search": {  
            "cosmosSearch": {  
                "vector": query_vector,  
                "path": "Embedding",  # vectorContent => Embedding
                "k": 2  
            },  
            "returnStoredSource": True  
        }  
    }  
]  
  
results = collection.aggregate(pipeline)  
  
for result in results:  
    print(result)  

When I run this code. I got the ServerSelectionTimeoutError.

ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connection refused, Timeout: 30s, Topology Description: <TopologyDescription id: 6481ed3e2a6be5698ffbd666, topology_type: Unknown, servers: [<ServerDescription (‘localhost’, 27017) server_type: Unknown, rtt: None, error=AutoReconnect(‘localhost:27017: [Errno 111] Connection refused’)>]>

I will solve the problem about ServerSelectionTimeoutError?
Note: I’ve tried changing the timeout but still can’t solve the problem.

Hey @Jaturong_Jaitrong,

The CosmosDB is a Microsoft product and is semi-compatible with a genuine MongoDB server. Hence, I cannot comment on how it works, or even know why it’s not behaving like a genuine MongoDB server.

At the moment of this writing, CosmosDB currently passes only 33.51% of MongoDB server tests , so I would encourage you to engage CosmosDB support regarding this issue.

To learn MongoDB, please refer to the MongoDB Univerisity, MongoDB DevCenter, and MongoDB Documentation.

Best regards,
Kushagra

1 Like