java - 在 $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);}
解决方案
你需要自动接线
@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游乐场
推荐阅读
- google-oauth-java-client - 使用适用于 java 的谷歌 OAuth2 客户端库访问 AzureAD API
- python - 通过 python 从 NetCDF 文件到 csv
- scala - value na 是不是成员?
- python - 具有多次出现的复杂字符串的 Pandas groupby 和 value 计数
- spring-boot - Spring Boot 2 执行器指标 - 处理器
- visual-studio - IIS Web 部署自动备份
- javascript - 使用十进制值添加数字不适用于 parseFloat
- python - Python正则表达式按前缀过滤
- jupyter-notebook - 如何在 google Collab 中打开文本文件
- angular - 如何根据使用 angular2 给出的输入过滤数据