How to properly disconnect MongoDB client - TagMerge
5How to properly disconnect MongoDB clientHow to properly disconnect MongoDB client

How to properly disconnect MongoDB client

Asked 5 months ago
5 answers

Your application needs the connected MongoDB client in your all services or repositories and therefore it is easier, if you have separated MongoDB client connect and disconnect functions in application package. You don't need to connect MongoDB client, if your server is starting, you can connect first if your services or repositories need the MongoDB client connection.

// db.go
package application

import (

var client *mongo.Client

func ResolveClientDB() *mongo.Client {
    if client != nil {
        return client

    var err error
    // TODO add to your .env.yml or .config.yml MONGODB_URI: mongodb://localhost:27017
    clientOptions := options.Client().ApplyURI(os.Getenv("MONGODB_URI"))
    client, err = mongo.Connect(context.Background(), clientOptions)
    if err != nil {

    // check the connection
    err = client.Ping(context.Background(), nil)
    if err != nil {

    // TODO optional you can log your connected MongoDB client
    return client

func CloseClientDB() {
    if client == nil {

    err := client.Disconnect(context.TODO())
    if err != nil {

    // TODO optional you can log your closed MongoDB client
    fmt.Println("Connection to MongoDB closed.")

In main:

func main() {
    // TODO add your main code here
    defer application.CloseClientDB()

In your repositories or services you can get now your MongoDB client easily:

// account_repository.go

// TODO add here your account repository interface
func (repository *accountRepository) getClient() *mongo.Client {
    if repository.client != nil {
        return repository.client
    repository.client = application.ResolveClientDB()
    return repository.client

func (repository *accountRepository) FindOneByFilter(filter bson.D) (*model.Account, error) {
    var account *model.Account
    collection := repository.getClient().Database("yourDB").Collection("account")
    err := collection.FindOne(context.Background(), filter).Decode(&account)
    return account, err

Source: link


The best way to do this in Python is to write your database connection as a singleton and then use the 'atexit' module to to decorate a function that disconnects. This ensures the connection is only instantiated once as we don't want to open multiple connections as we want to share one as well as at the end of your program the connection is disconnected.

import atexit
from pymongo import MongoClient

class MongoDB:
'''define class attributes'''
__instance = None

def getInstance():
    """ Static access method. """
    # if the instance doesnt exist envoke the constructor
    if MongoDB.__instance == None:
    # return instance
    return MongoDB.__instance

def __init__(self) -> None:
    """ Virtually private constructor. """
    if MongoDB.__instance != None:
        raise Exception("Singleton cannot be instantiated more than once")

        print("Creating MongoDB connection")
        # set instance and instance attributes
        self.client = MongoClient(config.CONNECTION_STRING)
        MongoDB.__instance = self

def closeConnection():
    Python '__del__' aka destructor dunder doesnt always get called
    mainly when program is terminated by ctrl-c so this method is decorated
    by 'atexit' which ensures this method is called upon program termination
    if MongoDB.__instance != None:
        print("Closing Connections")

If anyone knows of a better design pattern feel free to comment this is just something I came up with that seems to work well.

Hope this helps

Source: link


Imagine a Nancy module:
public class AuthorsModule : NancyModule
    public AuthorsModule()
        Get["/"] = _ => 
       	    var client = new MongoClient(connectionString);
       	    var server = client.GetServer();
       	    var library = server.GetDatabase("library");
       	    var authors = library.GetCollection("authors");

       	    var allAuthors = authors.FindAll();


       	    return allAuthors.ToList();

Source: link


Use close() method on your MongoClient instance:
client = pymongo.MongoClient()

# some code here

the safest way to close pymongo connection would be to use it with 'with'
with pymongo.MongoClient(db_config['HOST']) as client:
    db = client[ db_config['NAME']]
    item = db["document"].find_one({'id':1})

Source: link


Open the terminal and run the command:
sudo service mongod stop
Stop MongoDB Daemon ProcessFirst, you must stop the `mongod` process in your system to completely uninstall the mongoDB: Open the terminal and run the command:sudo service mongod stop
sudo apt-get purge mongodb-org*
In this step, we are going to tell you how to remove the mongoDB logs. We must know the mongoDB log location before removing them. MongoDB logs are kept inside /var/log/mongodb/.
sudo rm -r /var/log/mongodb
How to Remove MongoDB Logs?In this step, we are going to tell you how to remove the mongoDB logs. We must know the mongoDB log location before removing them. MongoDB logs are kept inside /var/log/mongodb/.sudo rm -r /var/log/mongodbGiven above command will remove the logs and its associated sub-directories.
sudo rm -r /var/lib/mongodb

Source: link

Recent Questions on mongodb

    Programming Languages