如何使用Spring Data MongoDB为每个用户获取最新记录?

时间:2018-08-25 20:21:03

标签: java mongodb spring-data spring-data-mongodb

我正在努力处理mongo查询。我需要在单个查询中找到文档集合。集合中应包含单个查询中每个用户的最新日期(字段createdAt)的文档。

Spock中有一个测试用例来说明我要达到的目标:

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)]
}

我发现2.1.0.M1版本中包含了不同的方法,因此它们尚不可用。

我也尝试使用@Query批注,但是文档(下面的链接)没有指定如何创建像我的查询。

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

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

无法通过Spring Data中的派生查询或使用MongoDB本机query operators来表达您要查找的查询。 Distinct也不会执行此操作,因为它只是将单个字段的不同值提取到数组中。

请考虑使用Aggregation。可以在reference documentation中找到有关Spring Data的详细信息。