According to Mongos Reference documentation on distinct operation:
Finds the distinct values for a specified field across a single collection or view and returns the results in an array.
In Spring Data MongoDB this can be achieved like this:
DistinctIterable<String> distinctIds =
mongoTemplate.getCollection(mongoTemplate.getCollectionName(Employee.class))
.distinct("id", String.class);
return Lists.newArrayList(distinctIds);
// or
BasicDBObject dbObject = new BasicDBObject();
dbObject.append("name", new BasicDBObject("$regex", ".*and.*"));
DistinctIterable<String> distinctIds =
mongoTemplate.getCollection(mongoTemplate.getCollectionName(Employee.class))
.distinct("id", dbObject, String.class);
return Lists.newArrayList(distinctIds);
MongoTemplate offers here a couple of overloads for distinct. The primer query will collect all IDs for entries of a employee collection directly while the latter one will perform a filtering for only IDs of employees that contain an and
within their name.
In order to convert the iterable result set to the requested List of String objects you can make use of Guava's newArray(...)
feature.
As @Veeram also mentioned in his comment you can of course also make use of a projected query like
Query query = Query.query(Criteria.where(...));
query.fields().include("id");
return mongoTemplate.find(query, String.class);
where query.fields().include("id")
is used to specify the fields you are actually interested in.
In contrast to distinct
, this approach will contain duplicate entries in the result list, if there are any. While an ID should in general be unique, performing these two queries on names might produce a result that contains multiple identical entries however.
While the answer given by @Boris is technically valid as well, it might have some performance impact, unfortunately, especially if lots of embedded and referenced documents need to get retrieved as well. I therefore would not recommend such an approach.
Final note: throughout the examples I have kept the Id
and Name
fields in lower-case letters as this is basically Java naming convention.