在MongoDB數(shù)據(jù)庫中我們可能需要對已有數(shù)據(jù)進(jìn)行聚合洒试,這里我簡單的描述一下如何進(jìn)行分組查詢,輸出自己想要的數(shù)據(jù)結(jié)果
//注入mongoDB模板
@Resource
private MongoTemplate mongoTemplate;
//這里我主要是想要查詢某個時間段的集合數(shù)據(jù)
//以下代碼對應(yīng)的mysql語句為 "select packageId,trackingId,openId from report group by trackingId where timestamp > " + startTime + " and timestamp < " + endTime
public List<MongoReport2Date> getMongoDataReport2Date(Long startTime,Long endTime){
Aggregation agg = Aggregation.newAggregation(
// 第一步:挑選所需的字段熟嫩,類似select *,*所代表的字段內(nèi)容
//因?yàn)槲业臄?shù)據(jù)是嵌套的對象褐捻,所以需要下面這種寫法
Aggregation.project("report.packageProgress.packageId", "report.packageProgress.trackingId", "report.packageProgress.openId","report.packageProgress.timestamp"),
// 第二步:sql where 語句篩選符合條件的記錄
Aggregation.match(
Criteria.where("packageProgress.timestamp").and("addedDate").gte(startTime).lte(endTime)),
// 第三步:分組條件掸茅,設(shè)置分組字段
Aggregation.group("packageProgress.trackingId")
.last("packageId").as("packageId")
.last("trackingId").as("trackingId")
.last("openId").as("openId"),
// 增加publishDate為分組后輸出的字段
// 第四步:重新挑選字段
Aggregation.project("packageId", "trackingId", "openId")
);
//將輸出的內(nèi)容編譯成我們自己想要的MongoReport2Date對象,這個對象Bean根據(jù)自己的需求創(chuàng)建
AggregationResults<MongoReport2Date> results = mongoTemplate.aggregate(agg, "report", MongoReport2Date.class);
List<MongoReport2Date> list = results.getMappedResults();
return list;
}