python-3.x 过滤pymongo list_collection_names抛出类型错误

c6ubokkw  于 2023-10-21  发布在  Python
关注(0)|答案(1)|浏览(87)

为什么下面的代码应该抛出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 ))

Pymongo 4.4.1

pgx2nnw8

pgx2nnw81#

试试这个:

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

避免使用内置变量(如filter)作为变量名是一个很好的做法,可以防止这种错误。

相关问题