mongodb,聚合查詢
命令格式:
db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)
示例:db.COLLECTION_NAME.aggregate(
[
{ "$match" : { "status" : { "$ne" : 4 } } }
{ "$group" : { "_id" : { "projectTreeName" : "$projectTreeName", "batchName" : "$batchName" } } },
{ "$sort" : { "_id.projectTreeName" : -1 } },
{$skip:2},
{$limit:3}
])
解讀:
mongodb的聚合查詢有個管道的概念,先執行完上一個管道,執行結果流入下一個管道。
上面這個例子就是:先執行 $match 再進入 $group 進行分組,然后對分組結果進行$sort排序,最后對查詢結果進行分頁設置。
java
我使用的是springboot 需要添加mongodb的依賴jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
application.properties的配置文件
spring.data.mongodb.uri=mongodb://username:password@localhost:27017/database
配置完成后,可以繼承MongoRepository進行基本增刪改查操作,這次主要討論分組查詢。
分組查詢使用mongotemplate 直接使用@Autowired進行自動裝配就行
import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;
@Autowired
private MongoTemplate mongoTemplate;
//方法中調用的newAggregation還有match,group,sort等管道函數都是org.springframework.data.mongodb.core.aggregation.Aggregation提供的靜態方法
Aggregation agg = newAggregation(
match(new Criteria("status").ne(4)),
group("batchName" ,"projectTreeName"),
sort(new Sort(Sort.Direction.DESC,"projectTreeName")),
skip(0L),
limit(10)
);
AggregationResults<Damweb_ClusterJob_jobs> aggregationResults = mongoTemplate.aggregate(agg,"COLLECTION_NAME", Damweb_ClusterJob_jobs.class);