SpringBoot操作Mongodb按时间段查询并按时间倒序

  • A+
所属分类:MongoDB

首先说明下,Mongodb中用的日期类型是ISODate,为了查询时通过日期过滤方便,所以我们插入数据时也需要插入ISODate型的数据,在Java中我们直接插入Date型Mongodb会自动帮我们转成ISODate型。

关键点就是用$gte,$lt比较日期,$gte就是>=的意思,$lt就是<的意思,

排序时需要传两个参数,第一个参数是按哪个字段排序,第二个参数是升序还是倒序,1表明升序,-1表明倒序

直接上代码吧。

// 设置查询条件
BasicDBObject doc = new BasicDBObject();
// 查询开始时间为去年同一时间
Date startTime = mongoService.getLastYearDate();
// 结束时间为当前时间
Date endTime = new Date();
doc.put("announceCreateTime", new BasicDBObject("$gte", startTime).append("$lt", endTime));
MongoCollection<Document> collection = mongoTemplate.getCollection(collectionName);
FindIterable<Document> result = collection.find(doc).sort(new BasicDBObject("createTime", -1));

 

ZPY

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: