spring - 如何对整个集合的数组大小求和?

标签 spring mongodb aggregation-framework spring-data-mongodb

我有 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/

相关文章:

mongodb - 首先按类别分组,然后按周或月分组

java - Spring MVC 网站管理/配置页面的推荐数据模型和数据源?

java - Spring 中使用的 XML Schema URL 是从什么时候开始仅支持 TLS1.2 的?

java - JPA 仅返回 @ManyToOne 对象的第一个实例

c# - 如何在 C# .Net 中使用 InsertOneAsync 将文档插入到 MongoDB 并返回相同的文档或其 ID

javascript - PUT方法 Mongoose 模型

MongoDB - $size 的参数必须是一个数组,但类型为 : EOO/missing

python - 选择要从 $lookup 返回的字段

java - Spring 框架: findBy throws Illegal Argument Exception

MongoDB 可选唯一索引