Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

187
Views
pymongo : to check if we have connected to MongoDB database
client = MongoClient('localhost',27017)
db = client[DB_NAME]

def db_connect():
    #connecting to a DB in mongoDB
    try:
        if client.get_database(DB_NAME):
            print("Connection Successful!")
            return True
    except:
        print("Please check your connection")
        return False

def db_close():
    print ("Connection Getting Closed")
    client.close()

I am trying to achieve a task, only if the connection exists by pymongo, then return True so that the functions can proceed, else it should return False and a message to check connection. So that we don't proceed further.

How can I achieve this?

EDIT 1 : Accepted Solution

Successfully added user: {
"user" : "ash",
"roles" : [
    {
        "role" : "readWrite",
        "db" : "myDB"
    },
    "clusterAdmin"
]

}

I added a user using the above code snippet and then used the following script.

DB_NAME = "myDB"
client = MongoClient('localhost',27017)
db = client[DB_NAME]
def db_connect():
    #connecting to a DB in mongoDB
    try:
        if db.authenticate("ash","password"):
            print("Connection Successful!")
            return True
    except:
        print("Please check your connection")
        return False

def db_close():
    print ("Connection Getting Closed")
    client.close()

if __name__ == "__main__":
    db_connect()
    db_close()

I have used this code snippet to connect to my DB Now getting connected to the DB I have the database in my PC and I am using Ubuntu 16.04.

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You will probably have to use the authenticate method anyway inside connection function, so you could do it as following:

In [12]: client = MongoClient(DB_MACHINE, DB_PORT)
In [13]: db = client.db_name
In [16]: if db.authenticate(DB_USER, DB_PASS, source=DB_SOURCE):
             # authenticated, do ...
         else:
             # not authenticated, not connected, do something else
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!