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

如何通过Spring Data MongoDB查询匹配条件的指定字段?

Solution to Fetch Only Specific Field in Spring Data MongoDB

Hey there! The issue you're facing is that by default, Spring Data MongoDB returns all fields when you run a query. To only fetch the categoryName field, you need to add a projection to your Query object to explicitly specify which fields to include (or exclude).

Modified Code with Projection

Here's how you can adjust your method to return only the categoryName field:

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

public ServiceList findOneByCategoryName(String categoryName) {
    Query query = new Query();
    query.addCriteria(Criteria.where("categoryName").is(categoryName));
    // Add projection to explicitly include only the categoryName field
    query.fields().include("categoryName");
    return mongoTemplate.findOne(query, ServiceList.class);
}

What This Does

  • The query.fields().include("categoryName") line tells MongoDB to only return the categoryName field in the query result.
  • The other fields in your ServiceList class (like id and serviceTypes) will be set to null since they aren't included in the response from MongoDB.

Optional: Return Just the String Value (More Efficient)

If you don't need the entire ServiceList object and only want the categoryName string, you can simplify the method for better efficiency:

public String findCategoryNameByCategoryName(String categoryName) {
    Query query = new Query();
    query.addCriteria(Criteria.where("categoryName").is(categoryName));
    query.fields().include("categoryName");
    
    ServiceList result = mongoTemplate.findOne(query, ServiceList.class);
    return result != null ? result.getCategoryName() : null;
    
    // Alternative approach to directly fetch the string value:
    // return mongoTemplate.findOne(query, String.class, "services");
}

Bonus: Exclude the Default _id Field

MongoDB returns the _id field by default even if you don't include it in your projection. If you want to exclude it entirely, add this line to your query:

query.fields().exclude("_id");

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 18:32:49