如何使用 Spring Framework Aggregation return 包含不同值的完整文档?

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

假设我有一些这样的文档:

{
   "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
}  

我想要 return 包含每个不同 GroupId 第一次出现的完整数据文档列表。我认为聚合是完成此类任务的最佳途径。这是我目前所拥有的:

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

应该注意的是,我不一定需要使用聚合,所以如果有一种方法可以使用简单的“查找”来实现,那么我可以接受。 我是 MongoDb 菜鸟,抱歉,如果我的“已尝试”部分不是很有用。然而,这就是我想要的:

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

试试这个。 $first 有助于获取第一次出现的数据

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();

工作Mongo playground