spring-mongodb

Retrieve MongoDB documents based on two fields with OR condition in Java Sprintboot application


I have a MongoDB collection with two documents like

{
"field1":"value1"
}

and

{
"field1":"value2"
"field2":"value1"
}

I want to retrieve both documents in my Springboot microservice.

Query query = new Query(Criteria.where("field1").is("value1").orOperator(Criteria.where("field2").is("value1")))
List<Something> list = mongoTemplate.find(query, Something.class);

The above code returns an empty list whereas the below code returns the first document.

Query query = new Query(Criteria.where("field1").is("value1"))
List<Something> list = mongoTemplate.find(query, Something.class);

How can I retrieve both documents?


Solution

  • You need to use syntax such as this, i.e. like orOperator(where1, where2) instead of where1.orOperator(where2):

    Criteria criteria1 = new Criteria();
            criteria1.orOperator(
                    Criteria.where("dumEmployeeId").is(user.getId()),
                    Criteria.where("toDumEmployeeId").is(user.getId())).
                    andOperator(
                        new Criteria().orOperator(
                                Criteria.where("priority").is("Important"),
                                Criteria.where("priority").is("Urgent")
                        )
                    );