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

Python3.10+PyMongo获取聚合查询执行时间报错求助

解决PyMongo聚合查询获取执行时间的报错问题

错误原因

你调用db.aluno.explain("executionStats").aggregate(pipeline_ref3)的方式有误,PyMongo的Collection对象没有explain()方法,因此抛出"Collection object is not callable"的错误。

正确实现方式

有两种可靠的方法获取聚合查询的executionTimeMillis:

方法一:直接在aggregate()中传入explain参数

将explain参数指定为"executionStats",直接获取包含执行统计的结果:

pipeline_ref3 = [
     {"$match": {"TP_FAIXA_ETARIA": {"$gte": 1, "$lte": 10}}},
     {"$lookup": {"from": "prova", "localField": "id_prova", "foreignField": "_id", "as": "dados_prova"}},
     {"$project":{"TP_FAIXA_ETARIA": 1,  "dados_prova.TX_RESPOSTAS_LC": 1, "dados_prova.TX_GABARITO_MT": 1 }}
] 

# 获取包含执行统计的解释结果
explain_result = db.aluno.aggregate(pipeline_ref3, explain="executionStats")
# 提取执行时间(毫秒)
execution_time = explain_result['executionStats']['executionTimeMillis']
print(f"聚合查询执行时间:{execution_time} 毫秒")

方法二:使用db.command()执行explain命令

通过MongoDB原生的explain命令来获取执行统计,这种方式更灵活,适合需要自定义verbosity的场景:

pipeline_ref3 = [
     {"$match": {"TP_FAIXA_ETARIA": {"$gte": 1, "$lte": 10}}},
     {"$lookup": {"from": "prova", "localField": "id_prova", "foreignField": "_id", "as": "dados_prova"}},
     {"$project":{"TP_FAIXA_ETARIA": 1,  "dados_prova.TX_RESPOSTAS_LC": 1, "dados_prova.TX_GABARITO_MT": 1 }}
] 

# 构造explain命令
explain_cmd = {
    "explain": {
        "aggregate": "aluno",  # 指定集合名
        "pipeline": pipeline_ref3,
        "cursor": {}  # 保持游标兼容性
    },
    "verbosity": "executionStats"  # 指定统计级别
}

# 执行命令并获取结果
result = db.command(explain_cmd)
# 提取执行时间
execution_time = result['executionStats']['executionTimeMillis']
print(f"聚合查询执行时间:{execution_time} 毫秒")

说明

  • 两种方法都不需要使用time.time()等外部计时库,直接获取MongoDB内部统计的查询执行时间。
  • executionStats级别会返回详细的执行统计,包括扫描文档数、索引使用情况以及核心的executionTimeMillis(查询执行耗时,单位毫秒)。

内容的提问来源于stack exchange,提问作者Spider-Man

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 07:30:19