使用PyMongo list_collection_names时为何抛出TypeError: 'dict' object is not callable
错误原因分析及修复方案
核心问题:变量名冲突
你定义了一个名为filter的字典变量,直接覆盖了Python内置的filter()函数。当最后一行尝试调用filter(lambda x: "test" in x, collection)时,实际调用的是前面那个字典对象——而字典是无法像函数一样被调用的,因此抛出TypeError: 'dict' object is not callable错误。
修复步骤
- 重命名自定义变量:把自定义的
filter字典改成其他名称,比如coll_filter,避免覆盖内置函数:coll_filter = {"name": {"$regex": r"^(?!system\.)"}} collection = mydb.list_collection_names(filter=coll_filter) - 可选优化:
mydb.list_collection_names()返回的本身就是列表,collection.sort()是原地排序,也可以用sorted()函数生成新的排序后列表,逻辑更直观:collection = sorted(mydb.list_collection_names(filter=coll_filter))
修复后完整代码
myclient = pymongo.MongoClient('x.x.x.x', username='xxxxxx', password='yyyyyyy', authSource='zzzz', authMechanism='SCRAM-SHA-256') mydb = myclient["db"] coll_filter = {"name": {"$regex": r"^(?!system\.)"}} collection = mydb.list_collection_names(filter=coll_filter) collection.sort() filtered_names = list(filter(lambda x: "test" in x, collection ))
内容的提问来源于stack exchange,提问作者Kay Gee
相关产品推荐
相关产品推荐

