title: How to get the newest record for every user using spring data mongodb?
body: <p>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 <code>createdAt</code>) for every user in single query.</p>
  
  <p>There is a test case in Spock to demonstrate what I am trying to acheive:</p>
  
  <pre><code>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)]
  }
  </code></pre>
  
  <p>I found that distinct methods are a part of <code>2.1.0.M1</code> version so they are not available yet. </p>
  
  <p>I was also trying with <code>@Query</code> annotation but the documentation (link below) does not specify how to create a query like mine.</p>
  
  <p><a href="https://docs.spring.io/spring-data/data-document/docs/current/reference/html/#d0e3309" rel="nofollow noreferrer">https://docs.spring.io/spring-data/data-document/docs/current/reference/html/#d0e3309</a></p>
  
  <p>Thanks for your help.</p>