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

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} 的余额记录")

排查步骤

  1. 核对账户ID拼写:确认列表中的账户ID与数据库中存储的完全一致(注意大小写、特殊字符、字母拼写)
  2. 单独测试查询:直接执行collections.find_one({"account_id": "alphanumric001"}),查看是否返回有效文档
  3. 检查字段完整性:如果查到文档,确认文档内包含historical_balances字段,且该字段是字典类型并包含目标日期的键

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 05:55:17