You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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错误。

修复步骤

  1. 重命名自定义变量:把自定义的filter字典改成其他名称,比如coll_filter,避免覆盖内置函数:
    coll_filter = {"name": {"$regex": r"^(?!system\.)"}}
    collection = mydb.list_collection_names(filter=coll_filter)
    
  2. 可选优化: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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 13:20:56