MongoTemplate 标准查询 [英] MongoTemplate Criteria Query

查看:85
本文介绍了MongoTemplate 标准查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在根据多个参数生成复杂的 Mongo 查询.我想用 Criteria 辅助类制定的标准之一是:

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

我试着用:

Criteria.where("field1").is(Criteria.where("$ne").is(false).and("$exists").is(true))

但它会产生:

{ "field1" : { $java : org.springframework.data.mongodb.core.query.Criteria@23864e60 } 

那么,如何实现我需要的确切查询?我无法对该查询字符串进行硬编码,因为这些类型标准是为 field1,...fieldN 动态生成的,然后与 $or 结合:

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

推荐答案

既然你不能使用 Criteria.and() 将多个条件添加到同一字段中,使用 Criteria.andOperator()如下:

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

这篇关于MongoTemplate 标准查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆