db.getCollection("device_measure").aggregate([{ $match: { createTime: { $gt: ISODate("2023-06-03 00:00:00"), $lt: ISODate("2023-06-04 00:00:00") }, familyId: 33 }, }, { $project: { outPower: { $toDouble: "$OutP" }, PvU: { $toDouble: "$PvU" }, PvP: { $toDouble: "$PvP" }, } }, { $group: { _id: "$familyId", avgField1: { $avg: "$outPower" }, avgField2: { $avg: "$PvU" }, avgField3: { $avg: "$PvP" }, } }])用mongoTemolate怎么写
时间: 2024-02-14 20:10:38 浏览: 306
您可以参考以下代码将该聚合操作转化为MongoTemplate的写法:
```
Criteria criteria = Criteria.where("createTime")
.gt("2023-06-03T00:00:00Z")
.lt("2023-06-04T00:00:00Z")
.and("familyId").is(33);
Aggregation aggregation = Aggregation.newAggregation(
Aggregation.match(criteria),
Aggregation.project()
.and(ConvertOperators.ToDouble.toDouble("$OutP")).as("outPower")
.and(ConvertOperators.ToDouble.toDouble("$PvU")).as("PvU")
.and(ConvertOperators.ToDouble.toDouble("$PvP")).as("PvP"),
Aggregation.group("familyId")
.avg("outPower").as("avgField1")
.avg("PvU").as("avgField2")
.avg("PvP").as("avgField3")
);
AggregationResults<Document> results = mongoTemplate.aggregate(aggregation, "device_measure", Document.class);
List<Document> mappedResults = results.getMappedResults();
```
其中,Criteria用于构建查询条件,Aggregation包含聚合操作的步骤,AggregationResults用于存储聚合结果。最后,您可以通过mappedResults获取聚合结果。
阅读全文