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()]));
noob
  • 774
  • 1
  • 10
  • 23
Aeteros
  • 643
  • 1
  • 10
  • 24

2 Answers2

38

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);
}
chridam
  • 100,957
  • 23
  • 236
  • 235
  • 1
    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"? – Aeteros Nov 05 '15 at 15:13
  • 2
    @Aeteros No perfomance issues at all. From the [docs](https://docs.mongodb.org/manual/reference/operator/query/and/), 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. – chridam Nov 05 '15 at 15:19
  • 1
    @chridam - thank you so much. Your solution worked perfectly. Gr8 Job!! – Srikumar Krishna Iyer Jan 22 '21 at 07:25
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));
Claus Nielsen
  • 334
  • 3
  • 8