mongodb内置的时间类是ISODate,当我们使用springdatamongo的时候,Spring 会将java.util.Date一直对应
而要想在数据库中对时间格式做相互转换的话,要注意时以下问题
new Date()
可以接受多种参数,如:
- YYYY-mm-dd
- YYYY-mm-ddTHH:MM:ss.
- YYYY-mm-ddTHH:MM:ssZ
- integer
- 标准时间格式
默认返回ISODate格式的时间, 时区是UTC
ISODate("2017-10-23T09:20:13Z")
Date()
默认返回当前时间,格式为当地标准时间格式
mongodb 中聚合查询可对时间做些处理
org.springframework.data.mongodb.core.aggregation.DateOperators
这是springdatamongodb对于时间类的方法类
public static Aggregation makeQuery(UserTrendDTO dto, String type) {
List<AggregationOperation> list = new ArrayList<>();
if (dto.getEndTime() != null) {
list.add(new MatchOperation(Criteria.where("createTime").lte(dto.getEndTime())));
}
if (dto.getStartTime() != null) {
list.add(new MatchOperation(Criteria.where("createTime").gte(dto.getStartTime())));
}
if (StringUtils.isNotBlank(dto.getObjectId())) {
list.add(new MatchOperation(Criteria.where("objectId").is(dto.getObjectId())));
}
if (StringUtils.isNotBlank(dto.getPath())) {
list.add(new MatchOperation(Criteria.where("path").is(dto.getPath())));
}
if (StringUtils.isNotBlank(dto.getSuperId())) {
list.add(new MatchOperation(Criteria.where("superId").is(dto.getSuperId())));
}
if (StringUtils.isNotBlank(dto.getSuperType())) {
list.add(new MatchOperation(Criteria.where("superType").is(dto.getSuperType())));
}
if (StringUtils.isNotBlank(dto.getType())) {
list.add(new MatchOperation(Criteria.where("type").is(dto.getType())));
}
if ("path".equals(type)) {
list.add(Aggregation.project("path", "createTime").and("_id").as("id"));
list.add(Aggregation.group("path").count().as("total"));
list.add(Aggregation.project("total").and("_id").as("path"));
list.add(Aggregation.sort(Sort.Direction.DESC, "path"));
} else {
list.add(Aggregation.project("createTime").and(
DateOperators.DateToString.dateOf("createTime").toString("%Y-%m-%d")
).as("date")
.and("_id").as("id"));
list.add(Aggregation.group("date").count().as("total"));
list.add(Aggregation.project("total").and("_id").as("createTime"));
list.add(Aggregation.sort(Sort.Direction.ASC, "createTime"));
}
Aggregation aggregation = Aggregation.newAggregation(
list.toArray(new AggregationOperation[list.size()])
);
return aggregation;
}
public List<UserTrendEntity> findAllForLine(UserTrendDTO dto, String type) {
Aggregation aggregation = makeQuery(dto, type);
AggregationResults<UserTrendEntity> results = mongoTemplate.aggregate(aggregation,
"user_collect", UserTrendEntity.class);
return results.getMappedResults();
}
网友评论