简体   繁体   中英

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.

Most of the examples of github have a 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.

This spring documentation provide the details, how to form a expression when you are want to fetch distinct values.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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