I'm generating a complicated Mongo
query depending on multiple parameters. One of criterion that I want to make with Criteria
helper class is:
{"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
:
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:
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
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")
));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.