MongoDB API Cannot connect to CosmosDB using URI string: No replica set members found yet

Dakarai McCoy 96 Reputation points
2021-02-26T17:48:43.49+00:00

Hello,

I am attempting to connect to the Azure CosmosDB using MongoDB API in python and am receiving a ServerSelectionTimeoutError. I am using the read-write key provided in the quickstart connection guide. The default timeout time is 30 seconds. Below is a test for connection with modification for a 1ms timeout error that also fails. I experimented with 0ms and even longer than 30 seconds with no success.

 `try:   
            client = pymongo.MongoClient(uri, serverSelectionTimeoutMS=1)   
            client.server_info()   
 except pymongo.errors.ServerSelectionTimeoutError as err:   
            print(err)`   

here is the error from the above code.

No replica set members found yet, Timeout: 0.001s, Topology Description: <TopologyDescription id: 6039226389effc87c5d93363, topology_type: ReplicaSetNoPrimary, servers: [<ServerDescription ('<server>.mongo.cosmos.azure.com', port) server_type: Unknown, rtt: None>]>

I even tried connecting using my local mongo shell but that isn't working either. I received a similar error with exit code 1. But checking the mongodb docs, there isn't an error code 1

C:\Program Files\MongoDB\Server\4.4\bin> mongo.exe <server>:port -u <uname> -p <password> == --tls --tlsAllowInvalidCertificates MongoDB shell version v4.4.3 connecting to: mongodb://<server>.mongo.cosmos.azure.com:port/test?compressors=disabled&gssapiServiceName=mongodb Error: couldn't connect to <server>.mongo.cosmos.azure.com, connection attempt failed: NetworkTimeout: Error connecting to <server>.mongo.cosmos.azure.com:port (IP) :: caused by :: Socket operation timed out : connect@src/mongo/shell/mongo.js:374:17 @(connect):2:6 exception: connect failed exiting with code 1

Do I need to configure the PyMongo API with some specific TLS settings? I checked the documentation and it suggests I might need to add a path to a *.pem file, however I didn't find any such suggestion in Azure ComosDB documentation (tutorials, how-to-guides, or quickstart).
Code and errors are modified for privacy.

Azure Cosmos DB
Azure Cosmos DB
An Azure NoSQL database service for app development.
1,483 questions
{count} votes

2 additional answers

Sort by: Most helpful
  1. Anurag Sharma 17,581 Reputation points
    2021-03-02T09:43:07.023+00:00

    Hi @Dakarai McCoy , welcome to Microsoft Q&A forum.

    I was trying to repro the error by connecting to Azure Cosmos DB Mongo DB API using python and was able to set similar error:

    pymongo.errors.ServerSelectionTimeoutError: xxxxxxxxxxxxxx.mongo.cosmos.azure.com:10255: timed out  
    

    Initially I though it could be a problem from the Azure Service itself but when I tried connecting from .NET code it worked fine. So did a little research and found an article which had similar issue:

    Connecting to a Microsoft Azure Cosmos DB with Python and the MongoDB API

    Made below changes in the connection string as per the above article and it worked fine:

    db_name = "test"  
    host = "xxxxxxxx.mongo.cosmos.azure.com"  
    port = 10255  
    username = "xxxxxxxx"  
    password = "xxxxxxxxx"  
    args = "ssl=true&retrywrites=false&ssl_cert_reqs=CERT_NONE"  
      
    connection_uri = f"mongodb://{username}:{password}@{host}:{port}/{db_name}?{args}"  
      
    client = MongoClient(connection_uri)  
      
    db = client[db_name]  
    user_collection = db['user']  
      
    # Save to the DB  
    user_collection.insert_one({"email": "test2@foobar.com"})  
      
    # Query the DB  
    for user in user_collection.find():  
        print(user)  
    

    Can you once try changing your code according to this and let us know if it works?

    ----------

    If answer helps, please mark it 'Accept Answer'

    0 comments No comments

  2. Dakarai McCoy 96 Reputation points
    2021-03-02T15:18:55.27+00:00

    HI @AnuragSharma-MSFT and @NevtejSaini-MSFT

    thank you for writing back.
    I tried the above with the arguments you suggested and still I receive this error. I should also let you know I've tried using the primary and secondary connection strings provided in the connection string associated with the server.

    connection_uri = f"mongodb://{username}:{password}@{host}:{port}/{db_name}?{args}"
    client = pymongo.MongoClient(connection_uri)
    client.server_info()

    Traceback (most recent call last) File "C:\Users\{user}\.conda\envs\ExcelPythonEnv\lib\site-packages\pymongo\topology.py", line 215, in _select_servers_loop raise ServerSelectionTimeoutError( pymongo.errors.ServerSelectionTimeoutError:<host>:10255: timed out, Timeout: 30s, Topology Description: <TopologyDescription id: 603e519daec6d693ca000877, topology_type: ReplicaSetNoPrimary, servers: [<ServerDescription (<host>, 10255) server_type: Unknown, rtt: None, error=NetworkTimeout('<host>:10255: timed out')>]>

    ` try:

            client = pymongo.MongoClient(uri, serverSelectionTimeoutMS=1)
            client.server_info() except pymongo.errors.ServerSelectionTimeoutError as err:
            print(err)'` 
    

    No replica set members found yet, Timeout: 0.001s, Topology Description: <TopologyDescription id: 603e454daec6d693ca000876, topology_type: ReplicaSetNoPrimary, servers: [<ServerDescription (<host>, 10255) server_type: Unknown, rtt: None>]>

    since I received another network error I don't think SSL/TLS is even able to attempt a secure connection. Seems I cannot find the host at all because rtt = None. So I checked the Microsoft management console and I don't see any certificates or keys. Not sure if I need to generate a new key pair.