【问题标题】:Spring-Data JPA Repository with MongoDB how to findAll elements using distinct with multiple fieldsSpring-Data JPA Repository with MongoDB 如何使用不同的字段查找所有元素
【发布时间】:2020-08-23 05:58:23
【问题描述】:

我有一个带有 SpringData 的应用程序,它使用存储库(接口)对 MongoDB 执行查询。

我想知道如何使用带有两个值的distinct 执行findAll 指令,即:

收藏:人

列:姓名、姓氏、地址

查找所有不同的用户(姓名和姓氏)。

【问题讨论】:

    标签: mongodb spring-data-mongodb distinct-values


    【解决方案1】:

    MongoDB distinct 允许跨集合检索单个字段的不同值,这与其他存储不同。您可以在 MongoDB 参考 documentation 中找到有关 distinct 的更多信息。

    为了检索多字段不同的值,您需要使用 $group aggregation,然后您可以通过 @Aggregation 应用。

    可能看起来像这样:

    { '$group': 
        { 
            '_id' : { '$concat' : ['$lastname', '$firstname'] },
            'lastname' : { '$first' : '$lastname' },
            'firstname' : { '$first' : '$firstname' }
        } 
    }
    
    @Aggregation("{ '$group' : { '_id' : { '$concat' : ...
    List<Person> findAllDistinctFirstnameLastname();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-11
      • 2018-05-22
      • 2016-12-10
      • 2017-11-23
      • 2015-01-12
      相关资源
      最近更新 更多