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
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-