MongoTemplate Criteria Query

后端 未结 2 469
小鲜肉
小鲜肉 2021-02-03 13:45

I\'m generating a complicated Mongo query depending on multiple parameters. One of criterion that I want to make with Criteria helper class is:

相关标签:
2条回答
  • 2021-02-03 14:36
    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));
    
    0 讨论(0)
  • 2021-02-03 14:39

    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);
    }
    
    0 讨论(0)
提交回复
热议问题