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

MongoDB Atlas Search调用aggregate报错:pipeline应为BSON文档却收到primitive.A

问题根因
  • 核心错误:aggregate方法要求传入由Python字典组成的列表作为聚合管道,你当前把$search阶段写成了JSON字符串,MongoDB无法识别该格式,所以抛出对应报错。
  • 附加问题:aggregate返回的是PyMongo游标对象,直接深拷贝无法拿到实际查询结果,需要先遍历游标转换成列表才能获取数据。
修正后代码
import copy
from flask import current_app, g
from pymongo import errors

def search_by_xyz(self, occasion_names, age_floor, age_ceiling, output_hash):
    # occasion names should be a list
    try:
        # 直接用Python字典定义聚合阶段,不要转成JSON字符串
        search_stage = { 
            "$search": { 
                "index": "prod_coll", 
                "$text": [{ 
                    "$query": ["birthday"], 
                    "path":"occasion" 
                }] 
            } 
        }
        print(search_stage)
        # 聚合管道是字典组成的列表
        result_cursor = g.db.prod_coll.aggregate([search_stage])
        # 先把游标转成列表再深拷贝,才能拿到实际数据
        result_list = list(result_cursor)
        output_hash = copy.deepcopy(result_list)
        print("The result is ", result_list)
        return True
    except errors.PyMongoError as e:
        current_app.logger.error(e)
        print("The error is ", e)
        return False
    except Exception as e:
        current_app.logger.error(e)
        print("The generic exception is ", e)
        return False
额外说明

如果你确实需要从JSON字符串加载聚合阶段,可以用json.loads()方法把字符串转成Python字典再传入管道,不要自行编码BSON,PyMongo会自动处理Python字典到BSON的转换。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 14:18:03