springmongodbspring-repositories

How can I create queries with sort and where in MongoDB with Spring Repository interface?


I am trying to make a specific query in a MongoDB collection with SpringBoot. There are lots of results with the query that can be seen here. I am trying to sort and filter the results as I did in MongoDB compass in the screenshot and get ONLY the latest entry in the query results.

TaskRepo.java

public interface TaskRepo extends MongoRepository<Task, String> { }

Solution

  • MongoRepository help you to query document with attributes of resource (entity), when you want to query with attributes of sub-resource (embedded entity) you can use @Query to declare finder queries directly on repository methods

    public interface TaskRepo extends MongoRepository<Task, String> {
    
        @Query("{'meta.idf' : ?0, 'method': ?1}).sort({'meta.date': -1}")
        public List<Task> findBySubResourceAndSort(String id, String method);
    }
    

    Or you can use MongoTemplate (refer this document https://docs.spring.io/spring-data/mongodb/docs/current/api/org/springframework/data/mongodb/core/MongoTemplate.html)