MongoTemplate Criteria Query
Asked Answered
H

2

14

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()]));
Haifa answered 5/11, 2015 at 14:3 Comment(0)
E
41

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);
}
Einkorn answered 5/11, 2015 at 14:14 Comment(3)
That generates following block { "$and" : [ { "field" : { "$exists" : true}} , { "field" : { "$ne" : false}}]} that is not exactly what I need, but logically it is. Wouldn't it result in perfomance issues because of doubling "field"?Haifa
@Haifa No perfomance issues at all. From the docs, MongoDB provides an implicit AND operation when specifying a comma separated list of expressions. Using an explicit AND with the $and operator is necessary when the same field or operator has to be specified in multiple expressions.Einkorn
@Einkorn - thank you so much. Your solution worked perfectly. Gr8 Job!!Cimex
D
0
Query query = new Query(Criteria.where("field1").exists(true).ne(false));

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

Query query = new Query(Criteria.where("field1").is(true));
Drusy answered 24/8, 2018 at 6:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.