spring mongodb分页,动态条件、字段查询
使用MongRepository
public interface VideoRepository extends MongoRepository<Video, String> {
Video findVideoById(String id);
// 视频分页预览{title,coverImg}
Page<Video> findByGradeAndCourse(Grade grade, Course course, Pageable page);
}
- 问题
- 动态条件查询?
- 只查询指定字段?
- 指定字段
@Query(fields = "{'title':1, 'coverImg':1, 'course':1}")
Page<Video> findBy(Criteria where, Pageable page);
- 指定条件
DBObject obj = new BasicDBObject();
obj.put("userId", new BasicDBObject("$gte", 2));
BasicDBObject fieldsObject = new BasicDBObject();
fieldsObject.put("userId", 1);
fieldsObject.put("name", 1);
Query query = new BasicQuery(obj.toString(), fieldsObject.toString());
- demo,使用MongoTemplate,Query,DBObject
@Override
public Result getVideos(Pageable page, Long gradeId, Long courseId) {
DBObject obj = new BasicDBObject();
if(gradeId!=null&&gradeId!=0){
obj.put("grade.id", gradeId);
}
if(gradeId!=null&&gradeId!=0){
obj.put("course.id", courseId);
}
obj.put("course.id", 2);
// obj.put("course.id", new BasicDBObject("$gte", 2));
BasicDBObject fieldsObject = new BasicDBObject();
fieldsObject.put("title", 1);
fieldsObject.put("coverImg", 1);
fieldsObject.put("course", 1);
Query query = new BasicQuery(obj.toString(), fieldsObject.toString());
query.skip(page.getOffset()).limit(page.getPageSize());
List<Video> videos = mongoTemplate.find(query, Video.class);
// 总个数
long count = mongoTemplate.count(query, Video.class);
Page<Video> result = new PageImpl<Video>(videos, page, count);
return Result.success(videos);
}
查询条件对于属性是对象(course)无法生效,该方法还是不可行
混合 (终极法器)
本质上还是使用MongoTemplate来实现的,MongoRepository能实现查询指定字段,但是不能实现动态条件查询。
MongoTemplate的find方法接收Query参数,Query可以实现动态字段,但是动态条件不是普适应的(我还没找到),对于对象属性无法查询。但是Query有一个addCriteria方法,该方法可以将Example融合到Query中。因此find方法使用了Example的动态查询,Query的动态字段查询。
- VidoeOperations
public interface VideoOperations {
Page<Video> findAllPage(Example<Video> example, DBObject fields, Pageable page);
}
- VideoRepository
public interface VideoRepository extends MongoRepository<Video, String>, VideoOperations {
Video findVideoById(String id);
}
- VideoRepositoryImpl
public class VideoRepositoryImpl implements VideoOperations {
@Autowired
private MongoTemplate mongoTemplate;
@Override
public Page<Video> findAllPage(Example<Video> example, DBObject fields, Pageable page) {
Query query = new BasicQuery(null, fields.toString());
query.addCriteria((new Criteria()).alike(example));
query.with(page);
// Query q = (new Query((new Criteria()).alike(example))).with(page);
List<Video> list = mongoTemplate.find(query, example.getProbeType());
return PageableExecutionUtils.getPage(list, page, () -> {
return mongoTemplate.count(query, example.getProbeType());
});
}
}
| Keyword | Sample | Logical result |
|---|---|---|
After |
findByBirthdateAfter(Date date) |
{"birthdate" : {"$gt" : date}} |
GreaterThan |
findByAgeGreaterThan(int age) |
{"age" : {"$gt" : age}} |
GreaterThanEqual |
findByAgeGreaterThanEqual(int age) |
{"age" : {"$gte" : age}} |
Before |
findByBirthdateBefore(Date date) |
{"birthdate" : {"$lt" : date}} |
LessThan |
findByAgeLessThan(int age) |
{"age" : {"$lt" : age}} |
LessThanEqual |
findByAgeLessThanEqual(int age) |
{"age" : {"$lte" : age}} |
Between |
findByAgeBetween(int from, int to) |
{"age" : {"$gt" : from, "$lt" : to}} |
In |
findByAgeIn(Collection ages) |
{"age" : {"$in" : [ages…]}} |
NotIn |
findByAgeNotIn(Collection ages) |
{"age" : {"$nin" : [ages…]}} |
IsNotNull, NotNull |
findByFirstnameNotNull() |
{"firstname" : {"$ne" : null}} |
IsNull, Null |
findByFirstnameNull() |
{"firstname" : null} |
Like, StartingWith, EndingWith |
findByFirstnameLike(String name) |
{"firstname" : name} (name as regex) |
NotLike, IsNotLike |
findByFirstnameNotLike(String name) |
{"firstname" : { "$not" : name }} (name as regex) |
Containing on String |
findByFirstnameContaining(String name) |
{"firstname" : name} (name as regex) |
NotContaining on String |
findByFirstnameNotContaining(String name) |
{"firstname" : { "$not" : name}} (name as regex) |
Containing on Collection |
findByAddressesContaining(Address address) |
{"addresses" : { "$in" : address}} |
NotContaining on Collection |
findByAddressesNotContaining(Address address) |
{"addresses" : { "$not" : { "$in" : address}}} |
Regex |
findByFirstnameRegex(String firstname) |
{"firstname" : {"$regex" : firstname }} |
(No keyword) |
findByFirstname(String name) |
{"firstname" : name} |
Not |
findByFirstnameNot(String name) |
{"firstname" : {"$ne" : name}} |
Near |
findByLocationNear(Point point) |
{"location" : {"$near" : [x,y]}} |
Near |
findByLocationNear(Point point, Distance max) |
{"location" : {"$near" : [x,y], "$maxDistance" : max}} |
Near |
findByLocationNear(Point point, Distance min, Distance max) |
{"location" : {"$near" : [x,y], "$minDistance" : min, "$maxDistance" : max}} |
Within |
findByLocationWithin(Circle circle) |
{"location" : {"$geoWithin" : {"$center" : [ [x, y], distance]}}} |
Within |
findByLocationWithin(Box box) |
{"location" : {"$geoWithin" : {"$box" : [ [x1, y1], x2, y2]}}} |
IsTrue, True |
findByActiveIsTrue() |
{"active" : true} |
IsFalse, False |
findByActiveIsFalse() |
{"active" : false} |
Exists |
findByLocationExists(boolean exists) |
{"location" : {"$exists" : exists }} |
spring mongodb分页,动态条件、字段查询的更多相关文章
- spring boot jpa 多条件组合查询带分页的案例
spring data jpa 是一个封装了hebernate的dao框架,用于单表操作特别的方便,当然也支持多表,只不过要写sql.对于单表操作,jpake可以通过各种api进行搞定,下面是一个对一 ...
- spring JPA分页排序条件查询
@RequestMapping("/listByPage") public Page<Production> listByPage(int page, int size ...
- mapper分页排序指定字段查询模板
StudentQuery: package Student; import java.util.ArrayList; import java.util.List; public class Stude ...
- 【spring data jpa】带有条件的查询后分页和不带条件查询后分页实现
一.不带有动态条件的查询 分页的实现 实例代码: controller:返回的是Page<>对象 @Controller @RequestMapping(value = "/eg ...
- MongoDB 分页查询的方法及性能
最近有点忙,本来有好多东西可以总结,Redis系列其实还应该有四.五.六...不过<Redis in Action>还没读完,等读完再来总结,不然太水,对不起读者. 自从上次Redis之后 ...
- C#MongoDB 分页查询的方法及性能
传统的SQL分页 传统的sql分页,所有的方案几乎是绕不开row_number的,对于需要各种排序,复杂查询的场景,row_number就是杀手锏.另外,针对现在的web很流行的poll/push加载 ...
- SpringDataJPA+QueryDSL玩转态动条件/投影查询
在本文之前,本应当专门有一篇博客讲解SpringDataJPA使用自带的Specification+JpaSpecificationExecutor去说明如何玩条件查询,但是看到新奇.编码更简单易懂的 ...
- Spring Boot Jpa 多条件查询+排序+分页
事情有点多,于是快一个月没写东西了,今天补上上次说的. JPA是Java Persistence API的简称,中文名Java持久层API,是JDK 5.0注解或XML描述对象-关系表的映射关系,并将 ...
- Spring Data JPA,一种动态条件查询的写法
我们在使用SpringData JPA框架时,进行条件查询,如果是固定条件的查询,我们可以使用符合框架规则的自定义方法以及@Query注解实现. 如果是查询条件是动态的,框架也提供了查询接口. Jpa ...
随机推荐
- js正则包含三位
var reg = new RegExp("^(?![A-Za-z]+$)(?![A-Z\\d]+$)(?![A-Z_\\W]+$)(?![a-z\\d]+$)(?![a-z_\\W]+$) ...
- Python数据分析之文本处理词频统计
1.项目背景: 原本计划着爬某房产网站的数据做点分析, 结果数据太烂了,链家网的数据干净点, 但都是新开楼盘,没有时间维度,分析意义不大. 学习的步伐不能ting,自然语言处理还的go on 2.分析 ...
- Python(简单计算器)
参考:https://www.cnblogs.com/alex3714/articles/5169958.html import re ret = re.search('\([^()]+\)','(1 ...
- 查看npm安装包版本
npm list 版本号. eg: npm list socket.io
- Django2.0 URL配置详解
转自:https://www.cnblogs.com/feixuelove1009/p/8399338.html Django2.0发布后,很多人都拥抱变化,加入了2的行列. 但是和1.11相比,2. ...
- python 对mongodb进行压力测试
最近对mongoDB数据库进行性能分析,需要对数据库进行加压. 加压时,最初采用threading模块写了个多线程程序,测试的效果不理想. 单机读数据库每秒请求数只能达到1000次/s.而开发的jav ...
- c++之随堂笔记
1.指针篇 给指针赋值时,只能等号右边只能使用&符号将一个对象的地址赋值给指针,不能直接把一个具体的数或者字符串直接赋值给指针. 举例: int* ptr_num = 100; //这种写法 ...
- ZJOI2019 day2 游记
应该是打的最没有信仰的一次比赛了 然后这个垃圾水平居然还拿了170,真是有毒 我的语文并不好所以还是写流水账吧 day-2 到了余姚,发现附近并没有什么好吃的,于是直接去kfc了 另外潮湿的空气对呼吸 ...
- 关于Vue中main.js,App.vue,index.html之间关系进行总结
在初始化的Vue项目中,我们最先接触到的就是main.js,App.vue,index.html这三个文件,我们从培训视频或者官方文档上可以了解到: index.html---主页,项目入口 App. ...
- python爬虫常用之Scrapy 中间件
一.概述 1.中间件的作用 在scrapy运行的整个过程中,对scrapy框架运行的某些步骤做一些适配自己项目的动作. 例如scrapy内置的HttpErrorMiddleware,可以在http请求 ...