简体   繁体   English

如何从 MongoRepository/QueryDSL 获取不同的字段?

[英]How do I get distinct fields from MongoRepository/QueryDSL?

My Document is我的文档是

@QueryEntity @Data @Document(collection = "MyCol") public class MyCol {
    @Id private String _id;
    private     String version;

I want to get all distinct version stored in the db.我想将所有不同的版本存储在数据库中。

My attempts:我的尝试:

public interface MyColDao extends MongoRepository<MyCol, String>, QueryDslPredicateExecutor<MyCol> {
    @Query("{ distinct : 'MyCol', key : 'version'}")
    List<String> findDistinctVersion();
}

Or just findDistinctVersion without the query annotation.或者只是没有查询注释的 findDistinctVersion。

Most of the examples of github have a By-field like大多数 github 的例子都有一个 By-field like

  List<Person> findDistinctPeopleByLastnameOrFirstname(String lastname, String firstname);

I don't need a By field.我不需要按字段。

Another example I found here .我在这里找到的另一个例子。

@Query("{ distinct : 'channel', key : 'game'}")
public JSONArray listDistinctGames();

This doesn't seem to work for me.这似乎对我不起作用。

I can't seem to find queryDSL/Morphia's documentation to do this.我似乎无法找到 queryDSL/Morphia 的文档来执行此操作。

This spring documentation provide the details, how to form a expression when you are want to fetch distinct values.这个 spring 文档提供了详细信息,当你想获取不同的值时如何形成一个表达式。

Link 关联

I had a similar problem, but I couldn't work out how to do it within the MongoRepository (as far as I can tell, it's not currently possible) so ended up using MongoTemplate instead.我有一个类似的问题,但我无法弄清楚如何在MongoRepository中做到这一点(据我所知,目前不可能)所以最终改用MongoTemplate

I believe the following would meet your requirement.我相信以下会满足您的要求。

@AutoWired
MongoTemplate mongoTemplate

public List<String> getVersions(){
    return mongoTemplate.findDistinct("version", MyCol.class, String.class);
}
   public interface MyColDao extends MongoRepository<MyCol, String>, QueryDslPredicateExecutor<MyCol> {
        @Query("{'yourdbfieldname':?0}")
        List<String> findDistinctVersion(String version);
    }

here version replaces your your db field name 此版本替换您的数据库字段名称
more you can see here 更多你可以在这里看到

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM