不能在pymongo的集合实例中使用find()

时间:2015-05-06 03:47:43

标签: python pymongo

我有一个班级:

import sys
import os
import pymongo
from pymongo import MongoClient

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()

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

我按如下方式创建了类实例:

    def getCollections(self):
        collections_dict = {}
        for i in range(len(self.db_collection_names)):
            collections_dict[self.db_collection_names[i]] = Collection(self.database_name, self.db_collection_names[i])
        return collections_dict

db_collection_names包含email_logs。我创建了一个emails实例,如下所示:

emails = collections_dict['email_logs']

print emails收益<collection.Collection instance at 0x105ce6248>

print emails.find()收益:

Traceback (most recent call last):
  File "main.py", line 75, in <module>
program.runProgram()
  File "main.py", line 63, in runProgram
print emails.find
AttributeError: Collection instance has no attribute 'find'

为什么会出错?

2 个答案:

答案 0 :(得分:0)

不确定为什么要重新定义Pymongo Collection课程。

from pymongo import MongoClient

db = MongoClient().my_database  # create an instance of pymongo Database
emails = db.emails  # create an instance of pymongo Collection

emails.find()  # yeilds a pymongo Cursor (containing the query results)

答案 1 :(得分:0)

我在find()方法

之前错过了这个集合
emails.collection.find()