epng
epng

Reputation: 11

Find multiple MongoDB records with different combination of values using Spring Data MongoDB criteria

I have a collection with first name, last name and birth year.

[
    {
        "firstName": "John",
        "lastName": "Smith",
        "birthYear": 1990
    },
    {
        "firstName": "Jane",
        "lastName": "Smith",
        "birthYear": 1989
    },
    {
        "firstName": "John",
        "lastName": "Doe",
        "birthYear": 1990
    },
    {
        "firstName": "Jane",
        "lastName": "Doe",
        "birthYear": 1990
    }
]

And I trying to find records with birthYear=1990 and ((firstName=John AND lastName=Smith) or (firstName=Jane AND lastName=Doe)).

The result I want is the following

[
    {
        "firstName": "John",
        "lastName": "Smith",
        "birthYear": 1990
    },
    {
        "firstName": "Jane",
        "lastName": "Doe",
        "birthYear": 1990
    }
]

Is there a way to do this using spring-data-mongodb's Query and Criteria?

Upvotes: 1

Views: 157

Answers (1)

varman
varman

Reputation: 8894

You may use Criteria query like

Query qa =
  Query.query(
      new Criteria()
          .orOperator(
              Criteria.where("firstName").is("John").and("lastName").is("Smith").and("birthYear").is(1990),
              Criteria.where("firstName").is("Jane").and("lastName").is("Doe")));

or you can write two jpa methods like findAllByFirstNameAndLastNameAndBirthYear(String firstName, String lastName, int birthYear) and findAllByFirstNameAndLastName(String firstName, String lastName) and combine both list together.

Upvotes: 0

Related Questions