Mr.Ustiik
Mr.Ustiik

Reputation: 345

How to retrieve only specific field of a document with Spring Data Mongo DB?

For example, I have a collection with the documents like:

class Group {
  @Id
  @Field( '_id' )
  UUID id

  @Field( 'title' )
  String title
}

I have a repository: interface GroupRepository extends MongoRepository<Group, UUID> { } How can I retrieve a list of all identifiers? I don't wanna retrieve all documents, and then collect the ids. I would like to have a method like: List<UUID> findAllGroupIds(). Is it possible without explicit implementation with Criteria? I've tried to use @Query, but it didn't give the result.

Upvotes: 0

Views: 713

Answers (1)

Ashish Bakwad
Ashish Bakwad

Reputation: 811

You can use the MongoDB aggregation framework to retrieve a list of ids.

Aggregation agg = newAggregation(stages.add(project("_id")));

AggregationResults<UUID> ids = mongoOperation.aggregate(agg,
                "Group", UUID.class);

Upvotes: 1

Related Questions