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

如何查询MongoDB数组中指定值的文档?求Spring Data/原生查询方案

查询爱好包含Teaching的学生文档方案

MongoDB Compass 原生查询语句

在MongoDB Compass的查询输入栏中,可直接使用以下语句匹配数组包含指定元素的文档:

{ "StudentHobby": "Teaching" }

若需支持多爱好匹配场景,也可显式使用$in操作符(单值匹配时效果与上方一致):

{ "StudentHobby": { "$in": ["Teaching"] } }

Spring Data MongoDB 实现方案

方法一:通过Query与Criteria构建查询

import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import java.util.List;

// 注入MongoTemplate实例
private final MongoTemplate mongoTemplate;

public List<Student> findStudentsWithTeachingHobby() {
    Query query = new Query(Criteria.where("StudentHobby").is("Teaching"));
    return mongoTemplate.find(query, Student.class);
}

方法二:使用Spring Data Repository派生查询

首先定义对应文档的实体类:

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import java.util.List;

@Document(collection = "students") // 替换为你的实际集合名称
public class Student {
    @Id
    private String id;
    private String StudentName;
    private int StudentAge;
    private String StudentCountryName;
    private List<String> StudentHobby;

    // 构造方法、Getter/Setter省略
}

然后定义Repository接口:

import org.springframework.data.mongodb.repository.MongoRepository;
import java.util.List;

public interface StudentRepository extends MongoRepository<Student, String> {
    // 派生查询规则:匹配爱好列表包含指定值的文档
    List<Student> findByStudentHobbyContaining(String hobby);
}

业务代码中直接调用Repository方法即可:

// 注入StudentRepository实例
private final StudentRepository studentRepository;

public List<Student> getStudentsWithTeachingHobby() {
    return studentRepository.findByStudentHobbyContaining("Teaching");
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 23:18:42