英文:
How do I return full documents containing a distinct value using Spring Framework Aggregation?
问题
{
"name" : "Wendy",
"phone" : "123",
"GroupId" : 1
},
{
"name" : "Sally",
"phone" : "345",
"GroupId" : 3
},
{
"name" : "Cortana",
"phone" : "567",
"GroupId" : 7
}
英文:
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
}
答案1
得分: 1
尝试这个。$first
用于获取数据的第一个出现。
Aggregation aggregation = Aggregation.newAggregation(
group("GroupId")
.first("name").as("name")
.first("GroupId").as("GroupId")
.first("phone").as("phone"),
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 上运行示例。
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论