Distinct in Spring Data MongoDB

前端 未结 7 1650
小鲜肉
小鲜肉 2021-01-04 00:28

Has anyone tried incorporating distinct in their query using Spring Data for Mongo. If you have an example can you please post it. Where and how sh

7条回答
  •  囚心锁ツ
    2021-01-04 00:31

    My environment: spring-data-mongodb 2.0.5,jdk1.8,

    Here is my code sample:

    import com.mongodb.client.DistinctIterable;
    import com.mongodb.client.MongoCollection;
    import com.mongodb.client.MongoCursor;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.data.mongodb.core.MongoTemplate;
    import org.springframework.stereotype.Repository;
    import java.util.ArrayList;
    import java.util.List;
    
    
    public List queryAllCategory() {
        List categoryList = new ArrayList<>();
        MongoCollection mongoCollection = mongoTemplate.getCollection("lexicon");
        DistinctIterable distinctIterable = mongoCollection.distinct("category",String.class);
        MongoCursor cursor = distinctIterable.iterator();
        while (cursor.hasNext()) {
            String category = (String)cursor.next();
            categoryList.add(category);
        }
        return categoryList;
    }
    

    about distinct method,please read: http://mongodb.github.io/mongo-java-driver/3.7/javadoc/com/mongodb/client/MongoCollection.html#distinct-java.lang.String-java.lang.Class-

提交回复
热议问题