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

Java MongoDB查询时过滤嵌套数组(保留指定条件元素)

MongoDB查询过滤嵌套数组元素(保留父文档)

需求说明

现有MongoDB集合数据结构如下:

{
    "_id" : "E00001",
    "name" : "Ramu",
    "totoList" : [
        {
            "mandatory" : false,
            "description" : "call customer care"
        },
        {
            "mandatory" : true,
            "description" : "get bill from person"
        }
    ]
}

需要通过mongoTemplate的查询类操作实现:

  • 保留所有员工文档,仅过滤嵌套数组totoList,移除其中mandatory: false的元素
  • 若过滤后totoList为空,则不返回该字段
  • 不使用$unset/$pull等更新类操作

解决方案:用聚合管道实现

普通find操作无法直接过滤嵌套数组元素,需要借助聚合管道处理数组,同时完整保留父文档。核心逻辑是用$filter筛选数组元素,再用条件判断决定是否保留该字段。

聚合管道逻辑

  1. 过滤数组元素:用$filter筛选totoList中mandatory: true的元素,生成临时字段
  2. 判断字段保留规则:用$cond结合$size判断过滤后的数组长度,若为0则不包含totoList字段,否则赋值为过滤后的数组

Spring Data MongoDB代码实现

import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationOperation;
import org.springframework.data.mongodb.core.aggregation.ArrayOperators;
import org.springframework.data.mongodb.core.query.Criteria;

import java.util.List;

// 第一步:过滤totoList数组,生成临时结果字段
AggregationOperation filterTotoList = Aggregation.addFields()
        .addFieldWithValue("filteredTotoList",
                ArrayOperators.Filter.filter("totoList")
                        .as("item")
                        .by(Criteria.where("item.mandatory").is(true)))
        .build();

// 第二步:根据临时字段的长度决定是否保留totoList
AggregationOperation projectFields = Aggregation.project("_id", "name")
        .and(Aggregation.ConditionalOperators.when(Criteria.where("filteredTotoList.size()").gt(0))
                .then("$filteredTotoList")
                .otherwise(null))
        .as("totoList")
        .andExclude("filteredTotoList");

// 组装并执行聚合查询
Aggregation aggregation = Aggregation.newAggregation(filterTotoList, projectFields);
List<Employee> empList = mongoTemplate.aggregate(aggregation, "employee", Employee.class).getMappedResults();

实体类注意事项

确保Employee类中的totoList字段支持null值,这样当数组为空时,序列化后不会包含该字段:

import org.springframework.data.annotation.Id;
import org.springframework.lang.Nullable;
import java.util.List;

public class Employee {
    @Id
    private String id;
    private String name;
    @Nullable
    private List<TodoItem> totoList;

    // getter、setter、构造方法省略

    public static class TodoItem {
        private boolean mandatory;
        private String description;

        // getter、setter、构造方法省略
    }
}

测试结果

  1. 存在符合条件的待办项时,返回结果:
{
    "_id" : "E00001",
    "name" : "Ramu",
    "totoList" : [
        {
            "mandatory" : true,
            "description" : "get bill from person"
        }
    ]
}
  1. 无符合条件的待办项时,返回结果:
{
    "_id" : "E00001",
    "name" : "Ramu"
}

内容的提问来源于stack exchange,提问作者Dickens A S

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 19:20:25