MongoDB语句:
db.point.aggregate([
{
$match: {
"code": {
$in: ["aaa", "bbb"]
},
"dataTime": {
"$lt": ISODate("2021-08-18 06:25:48.992"),
"$gt": ISODate("2021-08-17 06:25:48.992")
}
}
},
{
$group: {
_id: {
dataTime: {
$dateToString: {
format: "%Y-%m-%d %H:%M",
date: "$dataTime"
}
},
code:
"$code"
},
value: {
"$last": "$$ROOT"
}
}
},
{
$project: {
_id: "$value._id",
groupTime: "$_id",
pointId: "$value.pointId",
code: "$value.code",
dataTime: "$value.dataTime",
dataValue: "$value.dataValue",
_class: "$value._class"
}
},
{
$sort: {
"dataTime": - 1
}
}
])
转换为java代码:
//code字段in查询条件
List<String> pointDate = new ArrayList<>();
pointDate.add("aaa");
pointDate.add("bbb");
//时间区间查询条件
DateTime dateTimeStart = DateUtil.parse("2021-08-19T21:00:00.492+00:00");
DateTime dateTimeEnt = DateUtil.parse("2021-08-19T22:00:00.492+00:00");
Aggregation aggregation = Aggregation.newAggregation(
Aggregation.match(Criteria.where("code").in(pointDate).and("dataTime").gt(dateTimeStart).lt(dateTimeEnt)),
Aggregation.project("_id", "pointId", "code", "dataTime", "dataValue","dataTimeStr")
.andExpression("{$dateToString:{ format:'%Y-%m-%d %H:%M',date: '$dataTime'}}").as("dataTimeStr"),
Aggregation.group("code", "dataTimeStr")
.last("pointId").as("pointId")
.last("code").as("code")
.last("dataTime").as("dataTimeStr")
.last("dataValue").as("dataValue"),
Aggregation.sort(Sort.Direction.DESC, "dataTime"),
);
AggregationResults<PointData> results = mongoTemplate.aggregate(aggregation, "point", PointData.class);
JSONArray jsonArray = JSONUtil.parseArray(JSONUtil.parseObj(results.getRawResults()).get("results"));
System.out.println(jsonArray);
POM文件:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.6.3</version>
</dependency>