首页 > 解决方案 > 在 $group java mongoDB 之前按 $match 计算记录数

问题描述

我使用聚合从 MongoDB 中获取记录。在java中执行groupBy(MongoDB)之前,我需要计算$match返回的记录数。任何帮助将不胜感激。

             List countries =col2.distinct("country");
             for(int i=0;i<countries.size();i++){
                String country1= (String) countries.get(i);
                List<DBObject> pipeline = new ArrayList<DBObject>(Arrays.asList( 
                    new BasicDBObject("$match",new BasicDBObject("country", country1)),
                    new BasicDBObject("$group", 
                        new BasicDBObject("_id","$job_id" )
                          .append("count", new BasicDBObject("$sum",1)
                    ))));
                 AggregationOutput output = col2.aggregate(pipeline);}

这是一个示例数据: 在此处输入图像描述

标签: javamongodbaggregation-framework

解决方案


你需要自动接线

@Autowired
MongoTemplate mongoTemplate;

然后在java中转换后的mongo脚本

public List<Object> test(){
    Aggregation aggregation = Aggregation.newAggregation(
        
        match(Criteria.where("country").is("us")),
        group(null)
            .push("$$ROOT").as("data")
            .count().as("count")
        

    ).withOptions(AggregationOptions.builder().allowDiskUse(Boolean.TRUE).build());

    return mongoTemplate.aggregate(aggregation, mongoTemplate.getCollectionName(YOUR_COLLECTION.class), Object.class).getMappedResults();
}

我还没有测试过,但希望,这应该工作。

工作Mongo游乐场


推荐阅读