简体   繁体   中英

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> { }

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM