简体   繁体   中英

Pymongo Connection with MongoDB atlas - Error 111 Connection refused

I'm setting up a cron job, where it fetches some data from MongoDB atlas in Python3 through Pymongo in Cpanel. I always get a Error 111 Connnection refused.

I using python3.6 and pymongo-3.9.0, Cloud MongoDB-4.0.2

I have tried via SSHtunnel forwarder, but not sure how to give host_ip_addres, where MongoDB is in cluster

class DbConnection():
    def __init__(self):
        self.connectionServer = "mongodb+srv://"
        self.userName = "name"
        self.userPass = "pass"
        self.connectionCluster = "@temp-cluster0-lt2rb.mongodb.net"
        self.connectionDb = "developmentDB"

    def db_connect(self):
        ''' This function is used to connect to remote db with authentication
            Return type --> returns the url string of the db
            parameters--> self
            '''
        try:
            connectionUrl = self.connectionServer + self.userName + ":" + self.userPass + self.connectionCluster + "/test?retryWrites=true&w=majority"
            print(connectionUrl)
            myClient = pymongo.MongoClient(connectionUrl, port=12312)
            db = myClient.test
            print(myClient.test)

I'm expecting it to connect to the MongoDB cluster DB and read/Write the documents through it.

So the comments for the question solved the issue, so i'll just put this here for any future reference

The error can be resulted for must people because of a miss-configuration when moving from a self hosted MongoDB to a Remoted host service (Like MongoDB Atlas)

So, the +srv is DNS Seed List Connection Format .

When switching from port based connection to DNS seed based connection, we should remove any port configuration from our connection string, ie:

class DbConnection():
    def __init__(self):
        self.connectionServer = "mongodb+srv://"
        self.userName = "name"
        self.userPass = "pass"
        self.connectionCluster = "@temp-cluster0-lt2rb.mongodb.net"
        self.connectionDb = "developmentDB"

    def db_connect(self):
        ''' This function is used to connect to remote db with authentication
            Return type --> returns the url string of the db
            parameters--> self
            '''
        try:
            connectionUrl = self.connectionServer + self.userName + ":" + self.userPass + self.connectionCluster + "/test?retryWrites=true&w=majority"
            print(connectionUrl)
            // myClient = pymongo.MongoClient(connectionUrl, port=12312)
            // We remove the PORT 
            myClient = pymongo.MongoClient(connectionUrl)
            db = myClient.test
            print(myClient.test)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM