Java MongoTemplate 标准查询

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33546581/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 14:45:51  来源:igfitidea点击:

MongoTemplate Criteria Query

javamongodbspring-data-mongodbmongotemplate

提问by Aeteros

I'm generating a complicated Mongoquery depending on multiple parameters. One of criterion that I want to make with Criteriahelper class is:

我正在Mongo根据多个参数生成一个复杂的查询。我想用Criteria助手类制定的标准之一是:

{"field1": {$exists: true, $ne: false}}

I tried to make it with:

我试图做到这一点:

Criteria.where("field1").is(Criteria.where("$ne").is(false).and("$exists").is(true))

But it generates:

但它会产生:

{ "field1" : { $java : org.springframework.data.mongodb.core.query.Criteria@23864e60 } 

So, how to achieve the exact query that i need?I can't hardcode that query string, because these type criterions are generated dynamically for field1,...fieldN and then combined with $or:

那么,如何实现我需要的确切查询?我无法对该查询字符串进行硬编码,因为这些类型标准是为 field1,...fieldN 动态生成的,然后与$or

statusCriteria = statusCriteria.orOperator(criterias.toArray(new Criteria[criterias.size()]));

采纳答案by chridam

Since you can't use Criteria.and()to add multiple criteria into the same field, use Criteria.andOperator()as follows:

由于您不能使用Criteria.and()将多个条件添加到同一字段中,请Criteria.andOperator()按如下方式使用:

Query query = new Query();
query.addCriteria(
    new Criteria().andOperator(
        Criteria.where("field1").exists(true),
        Criteria.where("field1").ne(false)
    )
);

List<Foo> result = mongoTemplate.find(query, Foo.class);
System.out.println("query - " + query.toString());

for (Foo foo : result) {
    System.out.println("result - " + foo);
}

回答by Claus Nielsen

Query query = new Query(Criteria.where("field1").exists(true).ne(false));

Or, if field1 is always a boolean value when present:

或者,如果 field1 在出现时始终是布尔值:

Query query = new Query(Criteria.where("field1").is(true));