Do I need to close MongoDB client?

I'm working on a discord bot, but I'm not sure if I need to close the MongoClient with:

client.close()

The issue I have is that I'm returning some data from a collection, and obviously, I can't close the client after I return something.

If I need to close the client, what's the best way of doing it? At the moment, I have a discord command that returns something.

def get_queue_info(queue):
if queue.isdigit():
    queue = int(queue)
    return db['Groups'].find_one({"order":queue})
else:
    return db['Groups'].find_one({"name":str(queue).upper()})

#obviously, this won't work
#mongo.close()

My bot is executing commands pretty slowly, but I'm not sure if it's because of not closing

3 answers

  • answered 2021-05-03 18:09 Stoobish

    If you really want to manually close, here are a couple options:

    1. Call mongo.close() after you call get_queue_info(queue).
    2. Instead of just returning the data, save it to a var then close the connection and return the var.

    EDIT: upon looking it up, you don't need to manually close it. You should take advantage of connection pooling, just create one MongoClient that lasts for the entire life of your process. I think the reason your bot is executing commands pretty slowly is because MongoDB is taking so much CPU (review your schema or index design)

  • answered 2021-05-03 18:13 Belly Buster

    You don't need to close the connection. Pymongo manages the connection so there is no need to tidy it up.

  • answered 2021-05-03 18:30 Jonathon

    Thanks everyone. I guess I don't need to close the connection!