Search code examples
spring-data-mongodb

Spring Data MongoDB @Query with a Limit


Is there a way to add a limit to an @Query method in a Java or Kotlin MongoRepository class?

My query is basically the below and I'm trying to see if there's a way I can just put the limit into this level of the query instead of handling it later in the service layer.

@Query("{'area': { \$eq: ?0 }, \$and: [ /*some other logic*/ ]}, sort: {'dateUploaded': -1}, limit: ?1")
fun findLatestUploads(area: String, limit: Int): List<AudioFile>

The above actually executes but doesn't limit it to the limit = 5 value I put there when testing it.


Solution

  • In Spring Data MongoDB, the @Query annotation doesn't directly support the limit parameter as part of the query string. But you can limit the results returned to a desired number by renaming the method accordingly. E.g. if you want to retrieve the top 5 results, you can just name the method in that way. Spring Data follows convention over configuration approach i.e. interprets the desired result from the name of the method.

    interface AudioFileRepository : MongoRepository<AudioFile, String> {
        fun findTop5ByAreaOrderByDateUploadedDesc(area: String): List<AudioFile>
    }
    

    Note the name of the method findTop5ByAreaOrderByDateUploadedDesc.

    However, this method obviously hard codes the limit of the number of results to 5. If you want to do it dynamically, your only option is to do it in the service layer by creating a PageRequest object.