问题描述
{
"name" : "Wendy","phone" : "123","GroupId" : 1
},{
"name" : "Tom","phone" : "234",{
"name" : "Sally","phone" : "345","GroupId" : 3
},{
"name" : "Bob","phone" : "456",{
"name" : "Cortana","phone" : "567","GroupId" : 7
}
我想返回一个完整数据文档列表,其中包含每个不同的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","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();