使用MongRepository

public interface VideoRepository extends MongoRepository<Video, String> {
Video findVideoById(String id);
// 视频分页预览{title,coverImg}
Page<Video> findByGradeAndCourse(Grade grade, Course course, Pageable page);
}
  • 问题

    • 动态条件查询?
    • 只查询指定字段?
  1. 指定字段
@Query(fields = "{'title':1, 'coverImg':1, 'course':1}")
Page<Video> findBy(Criteria where, Pageable page);
  1. 指定条件
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分页,动态条件、字段查询的更多相关文章

  1. spring boot jpa 多条件组合查询带分页的案例

    spring data jpa 是一个封装了hebernate的dao框架,用于单表操作特别的方便,当然也支持多表,只不过要写sql.对于单表操作,jpake可以通过各种api进行搞定,下面是一个对一 ...

  2. spring JPA分页排序条件查询

    @RequestMapping("/listByPage") public Page<Production> listByPage(int page, int size ...

  3. mapper分页排序指定字段查询模板

    StudentQuery: package Student; import java.util.ArrayList; import java.util.List; public class Stude ...

  4. 【spring data jpa】带有条件的查询后分页和不带条件查询后分页实现

    一.不带有动态条件的查询 分页的实现 实例代码: controller:返回的是Page<>对象 @Controller @RequestMapping(value = "/eg ...

  5. MongoDB 分页查询的方法及性能

    最近有点忙,本来有好多东西可以总结,Redis系列其实还应该有四.五.六...不过<Redis in Action>还没读完,等读完再来总结,不然太水,对不起读者. 自从上次Redis之后 ...

  6. C#MongoDB 分页查询的方法及性能

    传统的SQL分页 传统的sql分页,所有的方案几乎是绕不开row_number的,对于需要各种排序,复杂查询的场景,row_number就是杀手锏.另外,针对现在的web很流行的poll/push加载 ...

  7. SpringDataJPA+QueryDSL玩转态动条件/投影查询

    在本文之前,本应当专门有一篇博客讲解SpringDataJPA使用自带的Specification+JpaSpecificationExecutor去说明如何玩条件查询,但是看到新奇.编码更简单易懂的 ...

  8. Spring Boot Jpa 多条件查询+排序+分页

    事情有点多,于是快一个月没写东西了,今天补上上次说的. JPA是Java Persistence API的简称,中文名Java持久层API,是JDK 5.0注解或XML描述对象-关系表的映射关系,并将 ...

  9. Spring Data JPA,一种动态条件查询的写法

    我们在使用SpringData JPA框架时,进行条件查询,如果是固定条件的查询,我们可以使用符合框架规则的自定义方法以及@Query注解实现. 如果是查询条件是动态的,框架也提供了查询接口. Jpa ...

随机推荐

  1. nova network-vif-plugged 事件分析1

    在创建虚机过程中,nova-compute会调用wait_for_instance_event函数(nova/compute/manage.py)进行network-vif-plugged的事件等待, ...

  2. Python----初次见面,请多关照!

    1.计算机的最基本认识 CPU(大脑) 3GHZ + 内存(DDR4) + 主板 + 电源(心脏)+ 显示器 + 键盘 +鼠标+ 显卡 + 硬盘 80MB/s 操作系统分为: windows 家用 l ...

  3. order by 使用注意

    create table user ( id int primary key, name varchar(11) , depid int ); create table dept( id int pr ...

  4. Verify the Developer App certificate for your account is trusted on your device.

    1.报错内容 Could not launch "CH5203" Verify the Developer App certificate for your account is ...

  5. IDEA去除 xml 中Sql语句的背景

    去掉黄色背景 去掉绿色背景

  6. java----session

    什么是session? 在WEB开发中,服务器可以为每个用户浏览器创建一个会话对象(session对象),也就是说他是保存在服务端的.注意:一个浏览器独占一个session对象(默认情况下).因此,在 ...

  7. Centos7.4下安装Redis5.0

    一.下载Redis Redis下载地址:https://redis.io/download 二.安装依赖包 安装Redis之前需要安装c++命令 yum install gcc-c++ 三.上传并解压 ...

  8. leetcode-31-下一个排列

    本题目在凌应标老师的<算法设计与分析>第八次作业中出现,可供参考. 题目描述: 实现获取下一个排列的函数,算法需要将给定数字序列重新排列成字典序中下一个更大的排列. 如果不存在下一个更大的 ...

  9. leetcode-733-Flood Fill

    题目描述: An image is represented by a 2-D array of integers, each integer representing the pixel value ...

  10. java开发注解大全

    目录 1.最基础注解(spring-context包下的org.springframework.stereotype) 1.1.@Controller @Service @Repository @Co ...