英文:
count the number of record by $match before $group java mongoDB
问题
我已经使用聚合功能从MongoDB中获取记录。在Java中,在进行分组(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);
}
英文:
I have used aggregation for fetching records from MongoDB. I need to count the number of records return by $match before I do the groupBy (MongoDB) in java. Any help will be appreciated.
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);}
答案1
得分: 0
你需要进行自动装配
@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 playground
英文:
You need to autowire
@Autowired
MongoTemplate mongoTemplate;
Then the converted mongo script in java
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();
}
I haven't tested it, but hope, this should work.
Working Mongo playground
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论