java 调用Mongo的聚合查询首先筛选出开始时间和结束时间相差大于一个小时的记录并按照任务名统计每个任务大于1小时的个数取出每个任务的最大时间间隔和最小时间间隔作为一个聚合查询返回最终结果
以下是使用Java调用MongoDB的聚合查询,筛选出开始时间和结束时间相差大于一个小时的记录,并按照任务名统计每个任务大于1小时的个数,取出每个任务的最大时间间隔和最小时间间隔,最后返回最终结果的示例代码:
import com.mongodb.MongoClient;
import com.mongodb.client.AggregateIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import java.util.Arrays;
public class MongoDBAggregationExample {
public static void main(String[] args) {
// 连接MongoDB
MongoClient mongoClient = new MongoClient("localhost", 27017);
// 获取数据库
MongoDatabase database = mongoClient.getDatabase("your_database");
// 获取集合
MongoCollection<Document> collection = database.getCollection("your_collection");
// 聚合查询条件:开始时间和结束时间相差大于一个小时
Document match = new Document("$match",
new Document("endTime",
new Document("$gt", new Document("$add", Arrays.asList("$startTime", 1000 * 60 * 60))))))
.append("$addFields",
new Document("timeDifference", new Document("$subtract", Arrays.asList("$endTime", "$startTime"))));
// 聚合查询:按任务名分组,统计每个任务大于1小时的个数,并取出最大时间间隔和最小时间间隔
Document group = new Document("$group",
new Document("_id", "$taskName")
.append("count", new Document("$sum",
new Document("$cond", Arrays.asList(new Document("$gt", Arrays.asList("$timeDifference", 1000 * 60 * 60)), 1, 0))))
.append("maxTimeInterval", new Document("$max", "$timeDifference"))
.append("minTimeInterval", new Document("$min", "$timeDifference")));
// 聚合查询结果
AggregateIterable<Document> result = collection.aggregate(Arrays.asList(match, group));
// 输出结果
for (Document document : result) {
System.out.println(document.toJson());
}
// 关闭连接
mongoClient.close();
}
}
请注意替换代码中的"your_database"和"your_collection"为实际的数据库名称和集合名称。此外,该代码假设开始时间和结束时间字段分别为startTime和endTime,任务名字段为taskName。
在聚合查询中,我们首先使用$match筛选出开始时间和结束时间相差大于一个小时的记录。然后使用$group进行分组,统计每个任务大于1小时的个数,并取出最大时间间隔和最小时间间隔。最后,我们通过aggregate方法执行聚合查询,并使用AggregateIterable迭代结果。
请根据实际情况调整代码中的查询条件和字段名称
原文地址: https://www.cveoy.top/t/topic/hBNY 著作权归作者所有。请勿转载和采集!