我有 mongodb json 数据:
{
"_id" : ObjectId("1111111111111111"),
"teamId" : "111",
"scoreId" : "50dcefb52d764ca3913985a80a4162ef",
"utterances" : [
{
"text" : "test1",
"parsedText" : "test1"
},
{
"text" : "test2",
"parsedText" : "test2"
}
]
},
{
"_id" : ObjectId("22222222222222"),
"teamId" : "111",
"scoreId" : "60dcefb52d764ca3913985a80a4162ef",
"utterances" : [
{
"text" : "do it1",
"parsedText" : "do it1"
},
{
"text" : "do it2",
"parsedText" : "do it2"
},
{
"text" : "do it3",
"parsedText" : "do it3"
}
]
}
mongo 查询如下:
db.teamScore.aggregate([
{$match : {teamId:"111"}},
{$unwind: '$utterances'},
{$group: {_id: '$_id', 'sum': { $sum: 1}}},
{$group: {_id: null, total_sum: {'$sum': '$sum'}}}
])
===>5
我想做的是使用 spring mongo 聚合计算总和话语
我正在尝试创建一个类似的来源:
Criteria creteria = Criteria.where("teamId").is("111");
MatchOperation matchStage = Aggregation.match(creteria);
GroupOperation group = group("scoreId")
.push("$utterances").as("utterances");
ProjectionOperation projectStage = project().and("scoreId").arrayElementAt(0).as("scoreId")
.and("utterances").size().as("count");
Aggregation aggregation = Aggregation.newAggregation(matchStage, unwind("utterances", true), group, projectStage);
AggregationResults<Intent> result = mongoTemplate.aggregate(aggregation, "intents", Intent.class);
List<Intent> results = result.getMappedResults();
如何计算话语数? 我是 mongodb 新手,所以给我一个解决这个问题的提示。 聚合是计算数组列表的最佳方法,对吗?
最佳答案
您可以将聚合简化为如下。
db.teamScore.aggregate([
{$match : {teamId:"111"}},
{$group: {_id: null, "total_sum": {"$sum": {"$size":"$utterances"}}}}
])
Spring 代码:
Criteria creteria = Criteria.where("teamId").is("111");
MatchOperation matchStage = Aggregation.match(creteria);
GroupOperation group = group()
.sum(ArrayOperators.Size.lengthOfArray("utterances")).as("count");
Aggregation aggregation = Aggregation.newAggregation(matchStage, group);
AggregationResults<Intent> result = mongoTemplate.aggregate(aggregation, "intents", Intent.class);
List<Intent> results = result.getMappedResults();
关于spring - 如何对整个集合的数组大小求和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49022490/