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

使用AggregationOperation unwind后分组如何保留Name、Job字段

MongoDB聚合查询丢失Name和Job字段的解决方法

样本数据

{
  "_id": ObjectId('63600a4cb7fa6706d181b2d1'),
  "Name": "Himanshu",
  "Job": "CEO",
  "Habits": [
    {
      "habitName": "football",
      "level": 3
    },
    {
      "habitName": "chess",
      "level": 5
    },
    {
      "habitName": "test",
      "level": 5
    }
  ]
}

需求

获取Name等于Himanshu的记录,并过滤Habits数组中仅保留level=5的元素。

尝试的代码

AggregationOperation main = Aggregation.match(Criteria.where("Name").is("Himanshu"));
AggregationOperation unwind = Aggregation.unwind("Habits");
AggregationOperation levelMatch = Aggregation.match(Criteria.where("Habits.level").is(5));
AggregationOperation group = Aggregation.group("$_id").push("Habits").as("Habits");

Aggregation ag = Aggregation.newAggregation(main, unwind, levelMatch, group);
System.out.println(ag);

AggregationResults<Pc> res = mg.aggregate(ag, "parent_child", Pc.class);

System.out.println(res.getMappedResults().toString());

当前输出

[Pc [_id=63600a4cb7fa6706d181b2d1, Name=null, Job=null, Habits=[HabitsDto [habitName=chess, level=5], HabitsDto [habitName=test, level=5]]]]

期望输出

[Pc [_id=63600a4cb7fa6706d181b2d1, Name=Himanshu, Job=CEO, Habits=[HabitsDto [habitName=chess, level=5], HabitsDto [habitName=test, level=5]]]]

解决方法

你的推测完全正确,问题出在group阶段没有包含Name和Job字段。unwind操作会把数组拆分成多条记录,但这些记录的Name和Job值都是相同的,所以可以用first()方法在group阶段保留这两个字段的原始值。

修改后的group操作代码如下:

AggregationOperation group = Aggregation.group("_id")
    .first("Name").as("Name")
    .first("Job").as("Job")
    .push("Habits").as("Habits");

替换原代码中的group操作后,聚合结果就能正确保留Name和Job字段的值了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 02:50:27