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
相关产品推荐
相关产品推荐

