ehsan shirzadi
ehsan shirzadi

Reputation: 4859

How to use mongodb collections like constants with pymongo

I want to use my MongoDB collections easily with constants. Currently I do it this way in my collections.py:

def db_nk():
    from pymongo import MongoClient
    con_nk = MongoClient()
    return con_nk['nk']

class collections:
    col_user_news_makers = db_nk()['esh_user_news_makers']
    col_user_news_groups = db_nk()['esh_user_news_groups']
    col_user_news_sources = db_nk()['esh_user_news_sources']

I import collections.py in each file and use them like this:

collections.col_users_bulletin_instances.insert({...})

I think it's not a good way because there are always open connections to Mongodb, but I don't know what is the best way. please guide me. thanks.
I have about 50 collections per project and there are 10 projects on a server simultaneously.

Upvotes: 0

Views: 268

Answers (1)

A. Jesse Jiryu Davis
A. Jesse Jiryu Davis

Reputation: 24027

There's nothing wrong with keeping one MongoClient open for the duration of your program, as the PyMongo FAQ says. But creating a new MongoClient for each collection creates an unnecessarily large number of connections and threads. Additionally, accessing all the collections and storing them as attributes of a "collections" class seems to be code complexity that has no advantage.

Easier to just create everything at the module global scope:

from pymongo import MongoClient
con_nk = MongoClient()
db = con_nk.nk

col_user_news_makers = db['esh_user_news_makers']
col_user_news_groups = db['esh_user_news_groups']
col_user_news_sources = db['esh_user_news_sources']

Upvotes: 1

Related Questions