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);
}
  • 问题
    • 动态条件查询?
    • 只查询指定字段?
  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());
        });
    }
}
KeywordSampleLogical result
AfterfindByBirthdateAfter(Date date){"birthdate" : {"$gt" : date}}
GreaterThanfindByAgeGreaterThan(int age){"age" : {"$gt" : age}}
GreaterThanEqualfindByAgeGreaterThanEqual(int age){"age" : {"$gte" : age}}
BeforefindByBirthdateBefore(Date date){"birthdate" : {"$lt" : date}}
LessThanfindByAgeLessThan(int age){"age" : {"$lt" : age}}
LessThanEqualfindByAgeLessThanEqual(int age){"age" : {"$lte" : age}}
BetweenfindByAgeBetween(int from, int to){"age" : {"$gt" : from, "$lt" : to}}
InfindByAgeIn(Collection ages){"age" : {"$in" : [ages…]}}
NotInfindByAgeNotIn(Collection ages){"age" : {"$nin" : [ages…]}}
IsNotNull, NotNullfindByFirstnameNotNull(){"firstname" : {"$ne" : null}}
IsNull, NullfindByFirstnameNull(){"firstname" : null}
Like, StartingWith, EndingWithfindByFirstnameLike(String name){"firstname" : name} (name as regex)
NotLike, IsNotLikefindByFirstnameNotLike(String name){"firstname" : { "$not" : name }} (name as regex)
Containing on StringfindByFirstnameContaining(String name){"firstname" : name} (name as regex)
NotContaining on StringfindByFirstnameNotContaining(String name){"firstname" : { "$not" : name}} (name as regex)
Containing on CollectionfindByAddressesContaining(Address address){"addresses" : { "$in" : address}}
NotContaining on CollectionfindByAddressesNotContaining(Address address){"addresses" : { "$not" : { "$in" : address}}}
RegexfindByFirstnameRegex(String firstname){"firstname" : {"$regex" : firstname }}
(No keyword)findByFirstname(String name){"firstname" : name}
NotfindByFirstnameNot(String name){"firstname" : {"$ne" : name}}
NearfindByLocationNear(Point point){"location" : {"$near" : [x,y]}}
NearfindByLocationNear(Point point, Distance max){"location" : {"$near" : [x,y], "$maxDistance" : max}}
NearfindByLocationNear(Point point, Distance min, Distance max){"location" : {"$near" : [x,y], "$minDistance" : min, "$maxDistance" : max}}
WithinfindByLocationWithin(Circle circle){"location" : {"$geoWithin" : {"$center" : [ [x, y], distance]}}}
WithinfindByLocationWithin(Box box){"location" : {"$geoWithin" : {"$box" : [ [x1, y1], x2, y2]}}}
IsTrue, TruefindByActiveIsTrue(){"active" : true}
IsFalse, FalsefindByActiveIsFalse(){"active" : false}
ExistsfindByLocationExists(boolean exists){"location" : {"$exists" : exists }}

转载于:https://www.cnblogs.com/zhuxiang1633/p/10647349.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值