我收到此错误TypeError:筛选器必须是dict,bson.son.SON或从集合继承的其他类型的实例。

时间:2019-04-22 05:15:59

标签: python mongodb python-collections

我正在将上次保存的数据检索到文本字段中,以便用户可以继续之前的工作,此命令在mongo控制台中可以正常工作,在PyCharm中,我无法找到编写find()的正确方法查询

我尝试将过滤器参数存储在此处建议的2个单独的变量中pymongo error: filter must be an instance of dict, bson.son.SON, or other type that inherits from collections.Mapping

Database.initialize()
db_data = Database.find(collection = 'notes_temp', 
                         query = ({"priority" : self.priority}, {'td': 1, '_id':0}))
        for task in db_data:
            self.t.insert('insert linestart', task)

数据库模块

class Database:
    URI = "mongodb://127.0.0.1:27017"
    DATABASE = None

    @staticmethod
    def initialize():
        client = pymongo.MongoClient(Database.URI)
        Database.DATABASE = client['notes']
    @staticmethod
    def find(collection, query):
        return Database.DATABASE[collection].find(query)

1 个答案:

答案 0 :(得分:1)

问题是您的查询定义为:

({"priority" : self.priority}, {'td': 1, '_id':0}))

所以当您的函数将其作为输入获取时,其解析为:

return Database.DATABASE[collection].find(({"priority" : self.priority}, {'td': 1, '_id':0})))

基本上还有一对应删除的括号。

一种模拟解决方案:(显然,有几种方法可以解决此问题)

Database.initialize()
db_data = Database.find(collection = 'notes_temp', 
                         query = {"priority" : self.priority}, projection = {'td': 1, '_id':0})
        for task in db_data:
            self.t.insert('insert linestart', task)

class Database:
    URI = "mongodb://127.0.0.1:27017"
    DATABASE = None

    @staticmethod
    def initialize():
        client = pymongo.MongoClient(Database.URI)
        Database.DATABASE = client['notes']
    @staticmethod
    def find(collection, query, projection):
        return Database.DATABASE[collection].find(query, projection)