PyMongo动态查询账户日余额报错求助
问题解决:动态账户ID查询余额报错处理
可能的报错原因
- 账户ID不存在于数据库:
find_one返回None,直接取['historical_balances']会触发AttributeError - 账户ID拼写错误:比如列表中的
alphanumric001少了字母e,与数据库中实际ID不匹配 - 目标账户文档无
historical_balances字段,或该字段下没有指定日期的记录
修正后的查询代码(带错误处理)
all_accounts = ['alphanumric001', 'alphanumeric002'] target_date = '2022-09-28' for account_id in all_accounts: # 查询账户文档 account_doc = collections.find_one({"account_id": account_id}) if not account_doc: print(f"账户 {account_id} 不存在") continue # 检查历史余额字段是否存在 if 'historical_balances' not in account_doc: print(f"账户 {account_id} 无历史余额数据") continue # 检查目标日期的余额记录 if target_date in account_doc['historical_balances']: balance = account_doc['historical_balances'][target_date] print(f"账户 {account_id} 在 {target_date} 的余额:{balance}") else: print(f"账户 {account_id} 无 {target_date} 的余额记录")
排查步骤
- 核对账户ID拼写:确认列表中的账户ID与数据库中存储的完全一致(注意大小写、特殊字符、字母拼写)
- 单独测试查询:直接执行
collections.find_one({"account_id": "alphanumric001"}),查看是否返回有效文档 - 检查字段完整性:如果查到文档,确认文档内包含
historical_balances字段,且该字段是字典类型并包含目标日期的键
内容的提问来源于stack exchange,提问作者Mier
相关产品推荐
相关产品推荐

