Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

200
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda