我的集合中有160.000个数据,我必须根据字段显示一些有关此数据的指标。所以我想我可以根据我的“域”字段对这些数据进行分组,并从数据库中获取汇总的数据。
我为分组数据创建了一个自定义存储库和一个模型,并运行以下代码,但是结果始终为空,但是,如果我在robo3t上使用记录的管道,则会得到所需的信息。
感谢您的帮助。
//customRepository
@Service
public class EventRecordRepositoryCustomImpl implements EventRecordRepositoryCustom {
private final MongoTemplate mongo;
@Autowired
public EventRecordRepositoryCustomImpl(MongoTemplate mongo) {
this.mongo = mongo;
}
@Override
public List<EventRecordCounts> query(String[] statuses) {
//MatchOperation match = Aggregation.match(new Criteria("status").not().in(Arrays.asList(statuses)));
GroupOperation group = Aggregation.group("domain").sum("relatedRecordCount").as("totalRelatedEventCount").count().as("totalMainEventCount");
AggregationOptions aggregationOptions = Aggregation.newAggregationOptions().explain(true).build();
Aggregation aggregation = Aggregation.newAggregation( group).withOptions(aggregationOptions);
AggregationResults<EventRecordCounts> result = mongo.aggregate(aggregation, mongo.getCollectionName(EventRecord.class), EventRecordCounts.class);
return result.getMappedResults();
}
}
//my collection: all getter and setters are provided
@Document(collection = "event_record")
public class EventRecord extends BaseModel {
private ObjectId collectorId;
@Indexed
private String recordNumber;
@Indexed
private String status;
private Long createdAt;
@Indexed
private Long updatedAt;
private Long finishedAt;
private String responsible;
private String responsibleUserName;
private String group;
private String type;
private String importance;
private String summary;
private Integer relatedRecordCount;
@Indexed
private String domain;
}
//Expected output model: all getter and setters are provided
public class EventRecordCounts {
@Field("_id")
private String _id;
private String domain;
private long openMainEventCount;
private long openRelatedEventCount;
private long totalMainEventCount;
private long totalRelatedEventCount;
}
将记录器切换到调试级别,并且仅记录以下信息。
2019-06-21 17:46:09,182 DEBUG o.s.data.mongodb.core.MongoTemplate - Executing aggregation: { "aggregate" : "event_record" , "pipeline" : [ { "$group" : { "_id" : "$domain" , "totalRelatedEventCount" : { "$sum" : "$relatedRecordCount"} , "totalMainEventCount" : { "$sum" : 1}}}] , "explain" : true}
如果我在robo3t中使用管道,那么结果也是预期的
答案 0 :(得分:1)
在对调试进行了一些调查之后,我发现了一个愚蠢的解决方案。我在AggregationResults.rawResults
类中使用键{firstBatch“和returnPotentiallyMappedResults
类中的方法MongoTemplate
在returnPotentiallyMappedResults
中获取数据,试图通过“结果”键进行获取。所以我写了一个CustomMongoTemplate并把Select a.ID, a.Activity, b.CompletedBy
FROM ActivityList a
LEFT JOIN ActivityLog b
ON a.ID = b.ActivityID AND b.CompletedBy = 'john@auto.com'
GROUP BY a.ID, a.Activity, b.CompletedBy