[英]MongoTemplate Criteria Query
I'm generating a complicated Mongo
query depending on multiple parameters.我正在根据多个参数生成一个复杂的Mongo
查询。 One of criterion that I want to make with Criteria
helper class is:我想用Criteria
helper class 制定的标准之一是:
{"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()]));
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);
}
Query query = new Query(Criteria.where("field1").exists(true).ne(false));
或者,如果field1在出现时总是一个布尔值:
Query query = new Query(Criteria.where("field1").is(true));
@Document(collection="student")
public class Student {
private String id;
private String name;
private List<String> subjects;
}
search a subject for list for student who have taken that subject.搜索一个科目以查找已修读该科目的学生的列表。
@Query("{'subjects':{$elemMatch:{$in:?0}}}")
public List<Student> getDrugByBrand(String[] subjects);
above is working but i want to create the query criteria.以上工作,但我想创建查询条件。
can any one convert {'subjects':{$elemMatch:{$in:?0}}} in to criteria任何人都可以将 {'subjects':{$elemMatch:{$in:?0}}} 转换为标准吗
i am trying like this but its not working我正在尝试这样但它不起作用
if(subject != null && ! subject()){
criteria.add(Criteria.where("subjects")
.elemMatch(Criteria.where("--what to put here for index--")
.regex(subject,"i")
));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.