Search code examples
python-3.xmongodbpymongo

filtering pymongo list_collection_names throws type error


Why should the following code throw TypeError: 'dict' object is not callable?

myclient = pymongo.MongoClient('x.x.x.x', username='xxxxxx', 
            password='yyyyyyy', authSource='zzzz', authMechanism='SCRAM-SHA-256')
mydb = myclient["db"]    
filter = {"name": {"$regex": r"^(?!system\.)"}}
collection = mydb.list_collection_names(filter=filter)
collection.sort()
filtered_names = list(filter(lambda x: "test" in x, collection ))

It is pymongo 4.4.1


Solution

  • Try this:

    myclient = pymongo.MongoClient('x.x.x.x', username='xxxxxx', 
                password='yyyyyyy', authSource='zzzz', authMechanism='SCRAM-SHA-256')
    mydb = myclient["db"]    
    my_filter = {"name": {"$regex": r"^(?!system\.)"}}
    collection = mydb.list_collection_names(filter=my_filter )
    collection.sort()
    filtered_names = list(filter(lambda x: "test" in x, collection ))
    

    Avoiding using built-ins (such as filter) as variable names is good practice and will prevent this kind of slip-up.