【问题标题】:How to get the newest record for every user using spring data mongodb?如何使用spring data mongodb获取每个用户的最新记录?
【发布时间】:2018-08-25 20:21:03
【问题描述】:

我正在为一个 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

感谢您的帮助。

【问题讨论】:

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


    【解决方案1】:

    无法通过 Spring Data 中的派生查询来表达您正在寻找的查询,也无法使用 MongoDB 原生 query operatorsDistinct 也不会完成这项工作,因为它只是将单个字段的不同值提取到数组中。

    请考虑使用Aggregation。 Spring Data 细节可以在reference documentation 中找到。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-26
      • 1970-01-01
      • 2015-10-30
      • 1970-01-01
      • 1970-01-01
      • 2011-01-25
      • 2023-01-22
      相关资源
      最近更新 更多