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

MongoDB数据读取异常:查询客户所属模块无结果问题排查

MongoDB查询异常修复方案

问题概况

首次读取MongoDB数据正常,修改数据库后出现异常:直接读取文档能获取真实数据,但调用查询客户所属模块的代码时返回空结果,部分场景提示客户不存在。

集合文档示例

E2C集合(客户-模块关联)

{'_id': ObjectId('65267b47b2396ab97ef1dc10'), 'Client__r.Name': 'Total', 'Module__r.Name': 'Oil','Module__r.Reference_Offre__c': 'O-AMP-CBA'}
{'_id': ObjectId('65267b47b2396ab97ef1dc11'), 'Client__r.Name': 'Shell', 'Module__r.Name': 'Gaz','Module__r.Reference_Offre__c': 'O-AMP-CAR'}

IF集合(模块-域关联)

{'Id Impact': 'a0b1r00000P0LOxAAN',
 'Module__r.Domain__r.Name': 'Heavy',
 'Module__r.Name': 'Oil',
  '_id': ObjectId('65267b74b2396ab97ef1ddbb')}
 {'Id Impact': 'a0b1r00000P0LOyAAN',
  'Module__r.Domain__r.Name': 'Light',
  'Module__r.Name': 'Gaz',
  '_id': ObjectId('65267b74b2396ab97ef1ddbc')}
 {'Id Impact': 'a0b1r00000P0LOzAAN',
  'Module__r.Domain__r.Name': 'Heavy',
  'Module__r.Name': 'Gaz',
  '_id': ObjectId('65267b74b2396ab97ef1ddbd')}

原代码问题分析

原查询代码存在三个核心错误:

  • 缩进错误:if client_info:块未缩进,导致函数逻辑无法正确执行
  • 字段匹配错误:E2C文档中不存在Modules字段,正确模块字段是Module__r.Name
  • 数据获取不全:使用find_one仅能获取客户的单个关联模块,无法提取所有模块

修复后的代码

def get_modules_and_domains_for_client(client_name):  
    # 查询客户所有关联的E2C文档,提取模块名称并去重
    client_docs = db["E2C"].find({"Client__r.Name": client_name})
    module_names = []
    for doc in client_docs:
        mod_name = doc.get("Module__r.Name")
        if mod_name and mod_name not in module_names:
            module_names.append(mod_name)
    
    if not module_names:
        return []
    
    # 匹配每个模块对应的域信息
    result = []
    for mod_name in module_names:
        module_doc = db["IF"].find_one({"Module__r.Name": mod_name})
        if module_doc:
            domain_name = module_doc.get("Module__r.Domain__r.Name", "")
            result.append({"Module__r.Name": mod_name, "Domain__r.Name": domain_name})
    
    return result

# 测试查询Total客户
client_name = "Total"  
modules_data = get_modules_and_domains_for_client(client_name)  
print(f"Modules possessed by the client {client_name}: {', '.join([item['Module__r.Name'] for item in modules_data])}")

# 测试查询Shell客户
client_name = "Shell"  
modules_data = get_modules_and_domains_for_client(client_name)  
print(f"Modules possessed by the client {client_name}: {', '.join([item['Module__r.Name'] for item in modules_data])}")

修复说明

  • 修正代码缩进,确保函数内逻辑正常执行
  • 使用find替代find_one,获取客户所有关联模块文档
  • 从Module__r.Name字段提取模块名称,同时做去重处理
  • 调整输出格式,匹配预期的结果展示要求

运行结果

  • 查询Total客户:Modules possessed by the client Total: Oil
  • 查询Shell客户:Modules possessed by the client Shell: Gaz

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 18:05:16