MongoDB 用MongoTemplate查询指定时间范围的数据

mongoDB大于小于符号对应:

> 大于 $gt
< 小于 $lt
>= 大于等于 $gte
<= 小于等于 $lte

要查询同一个时间多个约束可能出现的error:

org.springframework.data.mongodb.InvalidMongoDbApiUsageException: 
Due to limitations of the com.mongodb.BasicDocument, you can't add a second 'createdDate' expression specified as 'createdDate: 
Document{{$lt=2018-01-06}}'. Criteria already contains 'createdDate: Document{{$gte=2017-12-31}}'.

解决办法:
要查询同一个字段多个约束需要用andOperator:

Query query = new Query(
Criteria.where("ip").is(ip)
.andOperator(
Criteria.where("createdDate").lt(endDate),
Criteria.where("createdDate").gte(startDate)));

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MongoDB中,时间数据存储为ISODate对象。在Spring Data MongoDB中,可以使用MongoTemplate查询和操作MongoDB数据库。 要查询时间并将其格式化,可以使用Java中的SimpleDateFormat类。以下是一个示例代码,可以查询MongoDB中的时间字段,并将其格式化为指定的日期格式: ```java import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.TimeZone; public class Example { private MongoTemplate mongoTemplate; public Example(MongoTemplate mongoTemplate) { this.mongoTemplate = mongoTemplate; } public void queryAndFormatDate() { // 查询条件 Query query = new Query(Criteria.where("create_time").gte(new Date(1626940800000L))); // 查询2021-07-22之后的数据 // 查询结果 List<YourEntity> result = mongoTemplate.find(query, YourEntity.class); // 格式化时间 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); dateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai")); // 输出结果 for (YourEntity entity : result) { Date date = entity.getCreateTime(); String formattedDate = dateFormat.format(date); System.out.println(formattedDate); } } } ``` 上面的示例代码中,我们首先使用MongoTemplate查询MongoDB中的数据查询条件是文档中的`create_time`字段大于等于指定的日期。然后,我们获取查询结果,并使用SimpleDateFormat类将时间格式化为指定的日期格式。最后,我们输出格式化后的时间字符串。 需要注意的是,MongoDB中存储的时间是UTC时间,如果要将其转换为本地时间,需要使用TimeZone类设置时区。在上面的示例代码中,我们将时区设置为“Asia/Shanghai”。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值