以下是Java代码示例,演示如何使用MongoDB查询开始时间和结束时间相差大于一个小时的记录,并按照任务名统计每个任务大于1小时的个数,并获取每个任务的最大时间间隔和最小时间间隔。

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

import java.util.ArrayList;
import java.util.List;

public class MongoQuery {
    public static void main(String[] args) {
        // 连接MongoDB数据库
        MongoClient mongoClient = new MongoClient("localhost", 27017);
        MongoDatabase database = mongoClient.getDatabase("your_database_name");
        MongoCollection<Document> collection = database.getCollection("your_collection_name");

        // 查询开始时间和结束时间相差大于一个小时的记录
        Document query = new Document("endTime", new Document("$gt", "$startTime + 3600000"));
        List<Document> result = collection.find(query).into(new ArrayList<>());

        // 统计每个任务大于1小时的个数,并获取每个任务的最大时间间隔和最小时间间隔
        Document stats = new Document();
        for (Document document : result) {
            String taskName = document.getString("taskName");
            long startTime = document.getLong("startTime");
            long endTime = document.getLong("endTime");
            long duration = endTime - startTime;

            if (duration > 3600000) {
                // 统计任务个数
                int count = stats.getInteger(taskName, 0);
                stats.put(taskName, count + 1);

                // 更新最大时间间隔
                long maxDuration = stats.getLong(taskName + "_maxDuration", 0L);
                if (duration > maxDuration) {
                    stats.put(taskName + "_maxDuration", duration);
                }

                // 更新最小时间间隔
                long minDuration = stats.getLong(taskName + "_minDuration", Long.MAX_VALUE);
                if (duration < minDuration) {
                    stats.put(taskName + "_minDuration", duration);
                }
            }
        }

        System.out.println(stats);

        // 关闭MongoDB连接
        mongoClient.close();
    }
}

请注意替换代码中的以下部分:

  • your_database_name:您的MongoDB数据库名称。
  • your_collection_name:您的MongoDB集合名称。

此代码假设您的MongoDB集合中包含以下字段:

  • taskName:任务名称。
  • startTime:任务开始时间(以毫秒为单位的时间戳)。
  • endTime:任务结束时间(以毫秒为单位的时间戳)。

代码中的stats是一个Document对象,其结构如下:

{
  "task1": 10,               // 任务1大于1小时的个数
  "task1_maxDuration": 5000, // 任务1的最大时间间隔
  "task1_minDuration": 1000, // 任务1的最小时间间隔
  "task2": 5,                // 任务2大于1小时的个数
  "task2_maxDuration": 3000, // 任务2的最大时间间隔
  "task2_minDuration": 2000  // 任务2的最小时间间隔
}

请根据您的实际数据结构和字段名进行适当修改


原文地址: https://www.cveoy.top/t/topic/hBNl 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录