Cody Patterson
Cody Patterson

Reputation: 138

How do I return full documents containing a distinct value using Spring Framework Aggregation?

Say I have some documents like this:

{
   "name" : "Wendy",
   "phone" : "123",
   "GroupId" : 1
}, 
{
   "name" : "Tom",
   "phone" : "234",
   "GroupId" : 1
},
{
   "name" : "Sally",
   "phone" : "345",
   "GroupId" : 3
},
{
   "name" : "Bob",
   "phone" : "456",
   "GroupId" : 3
},
{
   "name" : "Cortana",
   "phone" : "567",
   "GroupId" : 7
}  

I'd like to return a list of full-data documents that contains the first occurrence of each distinct GroupId. I'm thinking Aggregation is the best route for a task like this. Here is what I have so far:

MatchOperation matchStage = Aggregation.match(new Criteria());
GroupOperation groupStage = Aggregation.group("GroupId").first("$$CURRENT").as("??");
// I know the above line is semi-nonsensical

Aggregation aggregation = Aggregation.newAggregation(matchStage, groupStage);

// I only need help creating the aggregation object, beyond this is just a MongoOperations aggregate call

It should be noted that I don't necessarily need to use aggregation so if there is a way to achieve this using a simple "find" then I'm okay with that. I'm a MongoDb noob, sorry if my "have tried" section is not very useful. However, this is what I would want back:

{
   "name" : "Wendy",
   "phone" : "123",
   "GroupId" : 1
}, 
{
   "name" : "Sally",
   "phone" : "345",
   "GroupId" : 3
},
{
   "name" : "Cortana",
   "phone" : "567",
   "GroupId" : 7
}

Upvotes: 1

Views: 136

Answers (1)

varman
varman

Reputation: 8894

Try this. $first helps to get the first occurrence of the data

Aggregation aggregation = Aggregation.newAggregation(
    group("GroupId")
        .first("name").as("name")
        .first("GroupId").as("GroupId")
        .first("phone").as("pnone"),
    project().andExclude("_id")
).withOptions(AggregationOptions.builder().allowDiskUse(Boolean.TRUE).build());

return mongoTemplate.aggregate(aggregation, mongoTemplate.getCollectionName(YOUR_COLLECTION_NAME.class), Object.class).getMappedResults();

Working Mongo playground

Upvotes: 1

Related Questions