'How do I use a custom created Query object on my repository in Spring boot app?

I am creating a Spring Boot application with MongoDB. I created a Query object that I would like to use to query my collection like so:

public Movie getRandomMovie(Integer top, String iso, Double minRating, Integer minVotes, Integer minYear, List<String> genres) {
    List <Criteria> criteria = new ArrayList<>();
    if (iso != null) {
        Locale l = new Locale("", iso);
        String country = l.getDisplayCountry();
        criteria.add(Criteria.where("country").is(country));
    }
    if (minRating != null) {
        criteria.add(Criteria.where("rating").gte(minRating));
    }
    if (minVotes != null) {
        criteria.add(Criteria.where("votes").gte(minVotes));
    }
    if (minYear != null) {
        criteria.add(Criteria.where("year").gte(minYear));
    }
    if (genres != null) {
        criteria.add(Criteria.where("genres").in(genres));
    }
    Criteria criterion = new Criteria();
    criterion.andOperator(criteria);
    Query query = new Query(criterion);
    return null;
}

My question is how to use this on my repository in order to only get documents that fit the criteria.



Solution 1:[1]

The easiest way in spring boot is via mongoTemplate. I write you some solution for the end of your function:

Criteria criterion = new Criteria();
criterion.andOperator(criteria);
Query query = new Query(criterion);

List<Movie> movies = mongoTemplate.find(query, Movie.class);
return movies.get(new Random().nextInt(movies.size()));

The mongoTemplate.find() will apply that query to the entityClass/Collection Movie. This will return a list of Movie documents that meet your query. Then we just return a random movie from the given list.

If you want to understand better how the MongoTemplate class works, I recommend having a look the documentation: MongoTemplate doc

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Paplusc