mongodb,聚合查询命令格式:db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)示例:db.COLLECTION_NAME.aggregate([ { $match : { status : { $ne : 4 } } } { $group : { _id : { proj...

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);
沃梦达教程
本文标题为:java mongodb groupby分组查询


猜你喜欢
- web开发之对比时间大小的工具函数的实例详解 2023-08-01
- MyBatis-Plus乐观锁插件的用法小结 2023-04-23
- Spring拦截器中注入Bean失败解放方案详解 2023-01-18
- 一文带你了解SpringBoot中常用注解的原理和使用 2023-07-01
- JSP页面跳转方法小结 2023-08-01
- Java正则表达式API Matcher类方法 2022-12-16
- spring mvc rest 接口选择性加密解密详情 2023-03-21
- springboot中如何通过main方法调用service或dao 2022-10-30
- springboot中的css样式显示不出了的几种情况 2023-06-23
- mybatis插入数据后如何返回新增数据的id值 2023-01-02