简体   繁体   English

使用Spring-Data-Mongo如何限制搜索?

[英]Using Spring-Data-Mongo how do I limit search?

Using Spring-Data-Mongo how do I limit search? 使用Spring-Data-Mongo如何限制搜索?

I am trying to find everyone over 19 but under 50 years old? 我想找到19岁以上但未满50岁的所有人吗? the field is called "age". 该字段称为“年龄”。 The following code is NOT working 以下代码不起作用

public void countUnderAge()
{
    List<Person> results = null;

    Query query = new Query();
    Criteria criteria = new Criteria();
    criteria = criteria.lte("21");

    query.addCriteria(criteria);
    results = mongoTemplate.find(query, Person.class);

    logger.info("Total number of under age in database: {}", results.size());
}

Use this: 用这个:

Query query= new Query();
query.addCriteria(where("age").lte(21)); 
List<Person> results = mongoTemplate.find(query, Person.class);

You are missing the field name of the where clause. 您缺少where子句的字段名称。 You can also do: 您也可以这样做:

Query query = new Query();
Criteria criteria = new Criteria();
criteria = where("age").lte("21");
query.addCriteria(criteria);

To use "where" you need to add this import: 要使用“ where”,您需要添加此导入:

import static org.springframework.data.mongodb.core.query.Criteria.where;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM