如何 select 具有 Mongodb 核心查询 API 的字段符合我的条件

How to select a field with Mongodb Core Query API matching my criteria

我需要 select 我的集合中只有一个字段名称 (categoryName) 符合我的条件。相反,所有字段都从以下代码的集合中返回:

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) {
    // TODO Auto-generated method stub
    Query query = new Query() ;
    query.addCriteria(Criteria.where("categoryName").is(categoryName));
    return (ServiceList) mongoTemplate.findOne(query,ServiceList.class);
}

ServiceList.java

@Document(collection = "services")
public class ServiceList {
    @Id
    private String id;
    
    @Field("categoryName")
    @JsonProperty("categoryName")
    private String categoryName;
    
    @Field("serviceTypes")
    @JsonProperty("Service Types")
    private List<ServiceType> serviceTypes;

    public String getMfServicesId() {
        return id;
    }

    public void setMfServicesId(String mfServicesId) {
        this.id = mfServicesId;
    }

    public String getCategoryName() {
        return categoryName;
    }

    public void setCategoryName(String categoryName) {
        this.categoryName = categoryName;
    }

    public List<ServiceType> getServiceTypes() {
        return serviceTypes;
    }

    public void setServiceTypes(List<ServiceType> serviceTypes) {
        this.serviceTypes = serviceTypes;
    }
    
 }

对于此代码,所有字段均从集合中返回。我不知道如何 select 我选择显示的特定字段。

我认为这可能有效,使用 fields() 方法:

Query query = new Query();
query.addCriteria(Criteria.where("categoryName").is(categoryName));
query.fields().include("categoryName");
query.fields().exclude("id"); // Not sure you have to exclude Id explicitly
return (String) mongoTemplate.findOne(query,String.class);

以下代码用于 select 并使用 include 函数显示文档中的特定列。

 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));
    query.fields().include("categoryName");
    return (ServiceList) mongoTemplate.findOne(query,ServiceList.class);
 }