wieczorekm
wieczorekm

Reputation: 158

How to get the newest record for every user using spring data mongodb?

I am struggling with a mongo query. I need to find a collection of documents in single query. The collection should contain document with newest date (field createdAt) for every user in single query.

There is a test case in Spock to demonstrate what I am trying to acheive:

def 'should filter the newest location for every user'() {
    given:
        List locationsInDb = [
            buildLocation(USERNAME_1, '2017-02-03T10:37:30.00Z'),
            buildLocation(USERNAME_1, '2017-03-04T10:37:30.00Z'),
            buildLocation(USERNAME_2, '2017-02-05T10:37:30.00Z'),
            buildLocation(USERNAME_2, '2017-03-06T10:37:30.00Z')
        ]
        insertToMongo(locationsInDb)
    when:
        List filteredLocations = locationRepository.findLastForEveryUser()
    then:
        filteredLocations == [locationsInDb.get(1), locationsInDb.get(3)]
}

I found that distinct methods are a part of 2.1.0.M1 version so they are not available yet.

I was also trying with @Query annotation but the documentation (link below) does not specify how to create a query like mine.

https://docs.spring.io/spring-data/data-document/docs/current/reference/html/#d0e3309

Thanks for your help.

Upvotes: 0

Views: 585

Answers (1)

Christoph Strobl
Christoph Strobl

Reputation: 6736

There are no means to express the query you are looking for via a derived query in Spring Data, nor using the MongoDB native query operators. Distinct as well will not do the job as it just extracts distinct values of a single field into an array.

Please consider using an Aggregation. Spring Data specifics can be found in the reference documentation.

Upvotes: 1

Related Questions