pom.xml(SpringBoot版本1.5.9)
<!-- 集成mongodb -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
配置文件
#mongodb配置
spring:
data:
mongodb:
host: ip
port: port
database: ismart
分頁查詢
@Autowired
private MongoTemplate mongoTemplate;
public void demo01() {
Criteria c = new Criteria();
if (params != null && params.size() > 0) {
for (Map.Entry<String, Object> entry : params.entrySet()) {
c.and(entry.getKey()).is(entry.getValue());
}
}
/**
* (num-1) * pageSize
* 1 10 0 10
* 2 10 10 10
* 3 10 20 10
*/
if (pageNum == null) {
pageNum = 1;
}
if (pageSize == null) {
pageSize = 10;
}
List<ReadingHistory> data = mongoTemplate.find(Query.query(c)
.with(new Sort(Sort.Direction.DESC, "mdbCreatedAt")) // 排序
.skip((pageNum - 1) * pageSize) //當(dāng)前頁
.limit(pageSize), // 每頁條數(shù)
ReadingHistory.class, "collectionHistory");
}
聚合查詢-根據(jù)時間分組、排序
????數(shù)據(jù)結(jié)構(gòu)如下圖
public void count() {
// 根據(jù)部門和時間統(tǒng)計上傳圖片數(shù)量搁宾,時間倒序
Aggregation agg = Aggregation.newAggregation(
// Aggregation.match(Criteria.where("moduleId").is("ismart")),
Aggregation.project("moduleId")
.and(DateOperators.DateToString.dateOf("createTime")
.toString("%Y-%m-%d")).as("date"),
Aggregation.group("date","moduleId").count().as("total"),
Aggregation.sort(Sort.Direction.DESC, "date","moduleId")
);
// 輸出數(shù)據(jù)
AggregationResults<JSONObject> a = mongoTemplate.aggregate(agg, "fastdfs", JSONObject.class);
System.out.println(a);
List<JSONObject> list = a.getMappedResults();
for (JSONObject count : list) {
System.out.println(count.toString());
}
}
輸出結(jié)果如下:
{"date":"2019-04-11","total":2,"moduleId":"ismart"}
{"date":"2019-04-11","total":750,"moduleId":"industrial"}
{"date":"2019-04-10","total":1239,"moduleId":"ismart"}
{"date":"2019-04-10","total":973,"moduleId":"industrial"}
{"date":"2019-04-08","total":1367,"moduleId":"ismart"}
{"date":"2019-04-08","total":2080,"moduleId":"industrial"}
...
- 需注意SpringBoot版本問題撕捍。使用1.5.9.RELEASE版本聚合查詢一直報錯(如上圖)摇锋,解決方案:升級SpringBoot版本至1.5.10.RELEASE驾霜。
聚合語法參考:
SQL 操作/函數(shù) | mongodb聚合操作 |
---|---|
where | $match |
group by | $group |
having | $match |
select | $project |
order by | $sort |
limit | $limit |
sum() | $sum |
count() | $sum |
join | $lookup(v3.2 新增) |
借鑒文章如下:
mongodb高級聚合查詢