Search code examples
pythonmongodbpython-collections

I get this error TypeError: filter must be an instance of dict, bson.son.SON, or other type that inherits from collections.Mapping


I am retrieving last saved data to a text field so the user can continue what they were working on earlier, this command works fine in mongo console, in PyCharm I can't figure out the right way to write the find() query

I tried storing filter parameters in 2 separate variables as suggested here 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)

database module

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)

Solution

  • The problem is your query is defined as :

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

    so when your function gets it as input its parsed as:

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

    Basically theres an extra pair of parentheses that should be removed.

    A mock up solution: (obviously there are several ways you can deal with this issue)

    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)