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

PyMongo获取字符串类型eosTimestamp最大值报错排查求助

错误原因及修复方案

核心错误

报错TypeError: name must be an instance of str的直接原因是:
你已经通过collection = mydb["properties"]获取了Collection对象,但后续调用client[db][collection].find()时,client[db]返回的Database对象要求传入字符串类型的集合名称,而你传入的是Collection实例,导致类型不匹配。

修复后的完整代码

def getLastEOSTimestampProperty(client, db):
    mydb = client[db]
    collection = mydb["properties"]
    # 替换废弃的ensure_index,改用create_index,可选添加背景创建参数避免阻塞
    collection.create_index([('eosTimestamp', -1)], background=True)
    filter = {}
    project = {'eosTimestamp': 1}
    sort = [('eosTimestamp', -1)]  # 简化sort定义,无需转字典items
    # 直接用已获取的collection对象调用find
    result = list(collection.find(
        filter=filter,
        projection=project,
        sort=sort
    ).limit(1))
    # 处理查询结果为空的边界情况,避免索引越界
    if not result:
        return None  # 可替换为你需要的默认值
    maxtimestamp = result[0]['eosTimestamp']
    return str(maxtimestamp)

额外优化点

  • ensure_index在PyMongo 3.0+版本已被废弃,推荐使用create_index,添加background=True可避免阻塞其他数据库操作。
  • sort参数可直接写成列表形式[('eosTimestamp', -1)],无需先定义字典再转成items列表,代码更简洁。
  • 增加结果为空的判断逻辑,防止集合无数据时出现IndexError: list index out of range。

内容的提问来源于stack exchange,提问作者Haggy2k3

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 12:25:17