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

MongoDB聚合查询Unwind操作报错:无效引用'result.detections'

问题解决:Spring Data MongoDB聚合Projection后Unwind报错

错误原因

你的Projection操作仅保留了result.detections.reference.control这个嵌套字段,执行完Projection后,原文档中的result.detections数组字段已被过滤移除。后续Unwind操作试图引用这个不存在的字段,因此抛出Invalid reference 'result.detections'错误。

解决方案

方案1:调整操作顺序(推荐)

先执行Unwind展开数组,再执行Projection保留需要的字段,逻辑更合理且避免字段缺失问题:

// 先展开detections数组
UnwindOperation unwindOpn = Aggregation.unwind("result.detections");

// 再投影需要的字段
ProjectionOperation projectionPostUnwind = Aggregation.project()
    .and("result.detections.reference.control").as("control");

Aggregation aggregation = Aggregation.newAggregation(unwindOpn, projectionPostUnwind);

LOGGER.info(" aggregation {}", aggregation);

AggregationResults<String> detectionsDataAggr = mongoTemplate.aggregate(aggregation, CASES_COLLECTION, String.class);

方案2:Projection时保留Unwind所需字段

若必须先执行Projection,需在Projection中明确保留result.detections数组字段,同时保留目标嵌套字段:

// 投影时同时保留result.detections数组和目标字段
ProjectionOperation projectionPreUnwind = Aggregation.project(
    Fields.from(
        Fields.field("result.detections"),
        Fields.field("result.detections.reference.control", "control")
    )
);

UnwindOperation unwindOpn = Aggregation.unwind("result.detections");

Aggregation aggregation = Aggregation.newAggregation(projectionPreUnwind, unwindOpn);

LOGGER.info(" aggregation {}", aggregation);

AggregationResults<String> detectionsDataAggr = mongoTemplate.aggregate(aggregation, CASES_COLLECTION, String.class);

说明

方案1更推荐,先展开数组再投影仅保留最终需要的数据,能减少数据传输量,提升聚合效率;方案2会先保留整个数组再展开,数据处理量相对更大。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 02:30:02