Home > Enterprise >  How to close MongoDB connection in Python?
How to close MongoDB connection in Python?

Time:02-22

Consider a python script like below which has many if else conditions and many try except blocks. I want to close the MongoDB connection after the MongoDB operations. Is the below mentioned way a proper way to close the connection?

def temp_fun():
    try:
        client = MongoClient(DB_NAME)  # from PyMongo
        if some_condition:
            # code 
            if client:
                client.close()
            return True
        elif some_condition:
            # code
            if client:
                client.close()
            return True
        else some_condition:
            # code
            if client:
                client.close()
            return True
    except:
        if client:
            client.close()
        return None

CodePudding user response:

You could try finally, as it's always executed regardless of the possible exceptions generated in code.

CodePudding user response:

You don't need to close pymongo connections, python and pymongo handles all the clean-up for you.

  • Related