我可以在 python 中将 mongodb 集合作为 class 属性吗

can I have a mongodb collection as a class attribute in python

我有以下 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

getIdFromEmail 时,我突然想到,每次我想从电子邮件中获取一个 ID,我都会创建另一个集合对象。有没有一种方法可以将对象作为 class 的一部分创建一次,而不是每次我想编写查询时都创建一个?

您的 collection 需要 self.dbself.collection_name 才能初始化,所以我认为您不能将其设为 class 属性。 我会在初始化 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)

您还可以使用属性,使您的 Collection 尽可能晚地连接到 MongoDB:

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

这些方法还有一个好处,当您导入 Collection.

时,不会连接到 MongoDB