MongoTemplate Criteria Query

不问归期 提交于 2019-12-04 13:29:42

问题


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

回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/33546581/mongotemplate-criteria-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!