Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

199
Vistas
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.

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

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
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda