使用聚合计算文档数量 MongoDB

Count number of documents using Aggregation MongoDB

我有 mongo 个文档,大致类似于

{
    "_id": {
              "$oid": "243234"
    },
    "category": ["cat1", "cat2"]
}

想要获取所有类别的计数,(即 cat1 = 20,cat2 = 7)
数字 20 和 7 是类别列表包含相应元素的文档数。

尝试在 mongo 模板中进行聚合,但我没有完全获得所需的预测结果。

投影模型:

public class CountModel{
    private String category;
    private Integer count;
}

我试过的代码:

GroupOperation categoryGroup = group("category").count().as("categoryCount");

ProjectionOperation projectionToModel = project()
   .andExpression("category").as("category")
   .andExpression("categoryCount").as("count");

Aggregation aggregation = newAggregation(categoryGroup, matchOperation, projectionToModel);

AggregationResults<PIICategoryCount> results = mongoTemplate.aggregate(aggregation,
   "repo_name",
    CountModel.class);
return results.getMappedResults();
     db.collection.aggregate([ {$unwind:"$category"}   , { $group:{ _id:"$category" , count: { $sum:1}}   } ])

谢谢@kiko075 的回答。

只需以 spring 启动可接受的形式给出答案。


// unwinds the document(have each document for each element in the list)
UnwindOperation unwindOperation = Aggregation.unwind("category");

// groups by the category which was unwound and counted
GroupOperation categoryGroup = Aggregation.group("category").count().as("categoryCount");

ProjectionOperation projectionToModel = project()
                    .andExpression("_id").as("category")         // _id refers to the unwound category (i.e, cat1)
                    .andExpression("categoryCount").as("count");

Aggregation aggregation = Aggregation.newAggregation(unwindOperation, categoryGroup, projectionToModel);

AggregationResults<CountModel> results = mongoTemplate.aggregate(aggregation,
                    "repo_name",
                    CountModel.class);
return results.getMappedResults();