pythonmongodbpymongo

Connect to MongoDB without password using pymongo


I'm a bit confused with the problem with pymongo and MongoDB.

I have a MongoDB server that I can connect using Studio 3T without any password (behind VPN): enter image description here enter image description here

mongodb://mongodb-dev.my.server:27017/?serverSelectionTimeoutMS=5000&connectTimeoutMS=10000

When I'm connecting to the server from Python I get error:

pymongo.errors.ServerSelectionTimeoutError: Could not reach any servers in [('mongodb-dev', 27017)]. Replica set is configured with internal hostnames or IPs?, Timeout: 5.0s, Topology Description: <TopologyDescription id: 6200d97072f39326314e6916, topology_type: ReplicaSetNoPrimary, servers: [<ServerDescription ('mongodb-dev', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('mongodb-dev:27017: [Errno 11001] getaddrinfo failed

Python script:

import pymongo

client = pymongo.MongoClient('mongodb://mongodb-dev.my.server:27017/?serverSelectionTimeoutMS=5000&connectTimeoutMS=10000')

db = client.get_database('feeeper')
col = db.get_collection('my_collection')

cur = col.find({}, {'body': 1})
last_task = cur.sort([('created', pymongo.DESCENDING)]).limit(1)

for t in last_task:
    print(t)

UPD: Ping to the server works fine: enter image description here

I can connect to the server with mongo shell: enter image description here


Solution

  • The problem is with default arguments for the MongoClient constructor. It has a directConnection parameter with default value of False — connect to replica set:

    directConnection (optional): if True, forces this client to connect directly to the specified MongoDB host as a standalone. If false, the client connects to the entire replica set of which the given MongoDB host(s) is a part. If this is True and a mongodb+srv:// URI or a URI containing multiple seeds is provided, an exception will be raised.

    When I passed directConnection as True the query worked fine.