MongoTemplate Criteria Query

Aeteros picture Aeteros · Nov 5, 2015 · Viewed 43.4k times · Source

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()]));

Answer

chridam picture chridam · Nov 5, 2015

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);
}