I have been learning myself MongoDB implementation in Spring Boot. However, I came into a problem with complex queries.
I cannot find any right solution for how to implement complex queries to MongoDB from Spring boot.
I am querying the database with MongoRepository interface implementation.
Let's say that I have three collections:
- Person - 1 Person can have many Pets.
- Pet - 1 Pet can have 1 PetToy and 1 Person who owns him.
- PetToy - 1 PetToy can belong to 1 Pet.
POJO classes are bellow
What do I want to achieve?
I want to make a query, which would be returned me a Person, whose Pet has a Toy (PetToy) with the name "Teddy".
I could not have found a way how to do it. Furthermore, is it the best practice to even use such complex queries, or is it better to write more of little ones in MongoDB?
POJOs:
@Document
@Data
@ToString
public class Person {
@Id
private String id;
private String firstname;
private String lastname;
private int age;
@DBRef
private Pet pet;
}
@Document
@Data
@ToString
public class Pet {
@Id
private String id;
private String name;
private int age;
@DBRef
private List<PetToy> toys;
}
@Document
@Data
@ToString
public class PetToy {
@Id
private String id;
private String name;
}
I have tried to use MongoRepositories; however, I was not able to make the complex query.
How can one write such a query to a MongoDB from Spring Boot?
Thank you very much in advance.