2

I have the following class:

import sys
import os
import pymongo
from pymongo import MongoClient

class Collection():

    client = MongoClient()

    def __init__(self, db, collection_name):
        self.db = db
        self.collection_name = collection_name

    def getCollection(self):
        data_base = getattr(self.client, self.db)
        collObject = getattr(data_base, self.collection_name)
        return collObject

    def getIdFromEmail(self, email):
        collection = self.getCollection()
        id = collection.find_one({"email":email},{"_id":1})
        return id

When writing getIdFromEmail it struck me that every time I want to get an id from an email, I'll be creating another collection object. Is there a way for the object to be created once as part of the class in stead of creating one every time I want to write a query?

Gaurav Dave
  • 6,838
  • 9
  • 25
  • 39
DBWeinstein
  • 8,605
  • 31
  • 73
  • 118

1 Answers1

1

Your collection needs both self.db and self.collection_name in order to be initialized, so I don't think you can make it a class attribute. I would just do all of this when initializing a Collection:

class Collection():
    def __init__(self, db, collection_name):
        self.db = db
        self.collection_name = collection_name

        if not hasattr(self.__class__, 'client'):
            self.__class__.client = MongoClient()

        database = getattr(self.client, self.db)
        self.collection = getattr(database, self.collection_name)

You can also use properties, which makes your Collection connect to MongoDB as late as possible:

class Collection():
    def __init__(self, db, collection_name):
        self.db = db
        self.collection_name = collection_name

    @property
    def client(self):
        if not hasattr(self.__class__, '_client'):
            self.__class__._client = MongoClient()

        return self.__class__._client

    @property
    def collection(self):
        if not hasattr(self, '_collection'):
            database = getattr(self.client, self.db)
            self._collection = getattr(database, self.collection_name)

        return self._collection

These methods also has the benefit of not connecting to MongoDB when you import Collection.

Blender
  • 289,723
  • 53
  • 439
  • 496