使用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. 代码审计之Catfish CMS v4.5.7后台作者权限越权两枚+存储型XSS一枚

    首先本地搭建环境,我所使用的是Windows PHPstudy集成环境.使用起来非常方便.特别是审计的时候.可以任意切换PHP版本. 本文作者:226safe Team – Poacher 0×01 ...

  2. elasticsearch5.2.1使用logstash同步mysql

    centos 本人亲测可以  首先安装好mysql,elasticsearch   不懂的请参考另一篇文章 安装logstash官方:https://www.elastic.co/guide/en/l ...

  3. 【javascript】—— JS判断浏览器类型、操作系统

    navigator.userAgent : userAgent 属性是一个只读的字符串,声明了浏览器用于 HTTP 请求的用户代理头的值. navigator.platform : platform ...

  4. mysql数据库中常用操作汇总

    一.查询数据库的基本信息: 1.    /* 查询数据库 ‘boss’ 所有表及注释 */SELECT TABLE_NAME,TABLE_COMMENT FROM information_schema ...

  5. Object中的方法以及对象相等的判定

    看图说话 Object有以下几个方法 getClass() final类型,主要是用来获得运行时的类型 hashCode() 返回该对象的哈希码值,方法是为了提高哈希表(例如 java.util.Ha ...

  6. Access to the path ‘’ is denied

    2019/4/29 问题:利用VS实现数据导出,出现Error:Access to the path 'F:\HPYMTotalCode\Web\dd\xmqjd.xls' is denied. 原因 ...

  7. html5: 复制到剪贴板 clipboard.js

    1.使用clipboard.min.js工具,引用此js 注意事项: IOS微信网页开发中,若使用此工具来开发复制功能,则需要在超链接/按钮上新增 onclick=" " 2.cl ...

  8. AES对称加解密

    简介设计思想加密模式ECB模式(电子密码本模式:Electronic codebook)CBC模式(密码分组链接:Cipher-block chaining)CFB模式(密文反馈:Cipher fee ...

  9. html5+js+.Net的即时多人聊天

            今天看了下websocket的知识,了解到这是html5新增的特性,主要用于实时web的通信.之前客户端获取服务端的数据,是通过客户端发出请求,服务端进行响应的模式,或者通过ajax每 ...

  10. Highcharts图表.net版开源,支持webform 和 mvc3,完全开源

    Highcharts是一个制作图表的纯Javascript类库,主要特性如下: 兼容性:兼容当今所有的浏览器,包括iPhone.IE和火狐等等: 对个人用户完全免费: 纯JS,无BS: 支持大部分的图 ...