[英]Spring Data MongoDB collection aggregation
I have some objects in MongoDB document, like this: 我在MongoDB文档中有一些对象,如下所示:
{
"_id" : ObjectId("0"),
"project" : "PRO",
"recruiters" : [
{
"userId" : "User1",
"fullName" : "UserName1"
}
],
}
{
"_id" : ObjectId("1"),
"project" : "PRO2",
"recruiters" : [
{
"userId" : "User1",
"fullName" : "UserName1"
}
],
}
{
"_id" : ObjectId("1"),
"project" : "PRO2",
"recruiters" : [
{
"userId" : "User1",
"fullName" : "UserName2"
}
],
How can I aggregate that document in Spring Data to result like this: 如何在Spring Data中聚合该文档,结果如下:
{
"Agg":[
{
"fullName":"UserName1",
"total":2
},
{
"fullName":"UserName2",
"total":1
}
]
}
I tried to do it some like this: 我尝试这样做:
Aggregation agg = newAggregation(
match(Criteria.where("project").is("project")),
group("recruiters").count().as("total"),
project("total").and("fullName").previousOperation(),
sort(Sort.Direction.DESC, "total"));
but I can't do it on collections. 但我不能在收藏品上做到这一点。 I want to group all fullName of "recruiters" in whole document and show them count. 我想在整个文档中对所有“招聘人员”的全名称进行分组并显示他们的数量。
Use $unwind
to convert the array into documents. 使用$unwind
将数组转换为文档。
Aggregation agg = newAggregation(
match(Criteria.where("project").is(project)),
unwind("recruiters"),
group("recruiters.fullName").count().as("total"),
project("total").and("fullName").previousOperation(),
sort(Sort.Direction.DESC, "total")
);
Try this:- with unwind() 试试这个: - 放松()
Aggregation agg = newAggregation(
match(Criteria.where("project").exists(true)),//if project field exist in document
unwind("recruiters"), // unwind the array of object
group("recruiters.fullName").count().as("total"),
project("total").and("fullName").previousOperation(),
sort(Sort.Direction.DESC, "total"));
Try this 尝试这个
MatchOperation matchOperation = Aggregation.match(Criteria.where("project").is("PRO"));
GroupOperation groupOperation = group("recruiters.fullName").count().as("total");
ProjectionOperation projectionOperation = project("total").and("fullName").previousOperation();
SortOperation sortOperation = sort(Sort.Direction.DESC, "total");
Aggregation aggregation = newAggregation(matchOperation, groupOperation, projectionOperation, sortOperation);
AggregationResults<DBObject> results = mongoTemplate.aggregate(aggregation, "YourCollectionName", DBObject.class);
Instead of DBObject
you can create a class mathcing the result and use that. 您可以创建一个算术结果并使用它来代替DBObject
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.