【MongoDB】使用mongoTemplate查询某个时间段的数据

使用mongoTemplate来查询数据库中某一个时间段的数据时,有两种方式:
第一种:使用时间戳

	@RequestMapping(value="/api/v2/timeInterval/users",method=RequestMethod.GET)
	@ApiImplicitParams({
		@ApiImplicitParam(name = "startTime", value = "开始时间戳,单位:ms", required = true, dataType = "Long", paramType = "query"),
		@ApiImplicitParam(name = "endTime", value = "结束时间戳,单位:ms", required = true, dataType = "Long", paramType = "query")})
	public ResponseEntity<?> getAllUserByUpdateTime(
			@RequestParam(name="startTime")Long startTime,
			@RequestParam(name="endTime")Long endTime){
		//  ...........其他代码忽略
		// long类型数据转化为时间戳
		Timestamp startTimestamp=new Timestamp(startTime);
		Timestamp endStTimestamp=new Timestamp(endTime);
		// 构建请求条件
		Criteria criteria = Criteria//
				.where("deletedStatus").is(Boolean.FALSE)//
				.andOperator(//
					new Criteria().and("updatedTimeStamp").gte(startTimestamp),
					new Criteria().and("updatedTimeStamp").lt(endStTimestamp));
		
	}

执行请求的Mongodb语句如下所示,时间已经被转化为了国标时间:

{ "deletedStatus" : false, "$and" : [ { "updatedTimeStamp" : { "$gte" : { "$date" : "2020-06-10T03:06:07.000Z"}}} , { "updatedTimeStamp" : { "$lt" : { "$date" : "2020-07-10T03:06:07.000Z"}}}] }

第二种:使用自定义格式的字符串语句,如:yyyy-MM-dd HH:mm:ss

	@RequestMapping(value="/api/v2/timeInterval/users",method=RequestMethod.GET)
	@ApiImplicitParams({
		@ApiImplicitParam(name = "startTime", value = "开始时间", required = true, dataType = "String", paramType = "query"),
		@ApiImplicitParam(name = "endTime", value = "结束时间", required = true, dataType = "String", paramType = "query")})
	public ResponseEntity<?> getAllUserByUpdateTime(
			@RequestParam(name="startTime")String startTime,
			@RequestParam(name="endTime")String endTime){
		//  ...........其他代码忽略
		DateTimeFormatter dateTimeFormatter=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
		LocalDateTime startLocalDateTime=LocalDateTime.parse(startTime, dateTimeFormatter);
		LocalDateTime endLocalDateTime=LocalDateTime.parse(endTime, dateTimeFormatter);
		// 构建请求条件
		Criteria criteria = Criteria//
				.where("deletedStatus").is(Boolean.FALSE)//
				.andOperator(//
					new Criteria().and("updatedTimeStamp").gte(startLocalDateTime),
					new Criteria().and("updatedTimeStamp").lt(endLocalDateTime));
		
	}

执行请求的Mongodb语句如下所示:

{ "deletedStatus" : false, "$and" : [ { "updatedTimeStamp" : { "$gte" : { "$date" : "1591758367000"}}} , { "updatedTimeStamp" : { "$lt" : { "$date" : "1594350367000"}}}] }

猜你喜欢

转载自blog.csdn.net/qgnczmnmn/article/details/107249908