You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Mongoose中按邮箱统计任务总耗时并转换为分钟

按邮箱统计用户任务总耗时(MongoDB/Mongoose)

优先方案:基于data.timer计算总耗时

timer字段为HH:MM:SS格式字符串,我们可以将其解析为秒数求和后转换为分钟格式(如120mins)。

聚合管道实现(推荐,数据库端处理)

利用MongoDB聚合管道直接在数据库完成计算,减少内存消耗:

YourModel.aggregate([
  // 解析每个timer为总秒数
  {
    $addFields: {
      dataSeconds: {
        $map: {
          input: "$data",
          as: "item",
          in: {
            $sum: [
              { $multiply: [{ $toInt: { $arrayElemAt: [{ $split: ["$$item.timer", ":"] }, 0] } }, 3600] },
              { $multiply: [{ $toInt: { $arrayElemAt: [{ $split: ["$$item.timer", ":"] }, 1] } }, 60] },
              { $toInt: { $arrayElemAt: [{ $split: ["$$item.timer", ":"] }, 2] } }
            ]
          }
        }
      }
    }
  },
  // 求和并转换为分钟格式
  {
    $addFields: {
      totalTime: {
        $concat: [
          { $toString: { $round: { $divide: [{ $sum: "$dataSeconds" }, 60] } } },
          "mins"
        ]
      }
    }
  },
  // 保留目标字段
  {
    $project: {
      _id: 1,
      taskCount: 1,
      totalTime: 1
    }
  }
]).exec()

代码端处理

如果需要在Node.js中处理查询结果:

const calcTotalFromTimer = (data) => {
  let totalSec = 0;
  data.forEach(item => {
    const [h, m, s] = item.timer.split(':').map(Number);
    totalSec += h * 3600 + m * 60 + s;
  });
  return `${Math.round(totalSec / 60)}mins`;
};

// 查询后处理结果
YourModel.find({}).then(docs => {
  const stats = docs.map(doc => ({
    email: doc._id,
    taskCount: doc.taskCount,
    totalTime: calcTotalFromTimer(doc.data)
  }));
  console.log(stats);
});

备选方案:基于data.date与data.start的时间差计算

当timer字段不可用时,通过计算任务结束时间与开始时间的差值求和:

聚合管道实现

YourModel.aggregate([
  // 计算每个任务的耗时秒数
  {
    $addFields: {
      dataSeconds: {
        $map: {
          input: "$data",
          as: "item",
          in: {
            $divide: [
              { $subtract: [{ $toDate: "$$item.date" }, { $toDate: "$$item.start" }] },
              1000 // 毫秒转秒
            ]
          }
        }
      }
    }
  },
  // 求和转分钟格式
  {
    $addFields: {
      totalTime: {
        $concat: [
          { $toString: { $round: { $divide: [{ $sum: "$dataSeconds" }, 60] } } },
          "mins"
        ]
      }
    }
  },
  {
    $project: {
      _id: 1,
      taskCount: 1,
      totalTime: 1
    }
  }
]).exec()

代码端处理

const calcTotalFromDates = (data) => {
  let totalSec = 0;
  data.forEach(item => {
    const end = new Date(item.date);
    const start = new Date(item.start);
    totalSec += (end - start) / 1000;
  });
  return `${Math.round(totalSec / 60)}mins`;
};

YourModel.find({}).then(docs => {
  const stats = docs.map(doc => ({
    email: doc._id,
    taskCount: doc.taskCount,
    totalTime: calcTotalFromDates(doc.data)
  }));
  console.log(stats);
});

内容的提问来源于stack exchange,提问作者MR. Mentor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 22:40:48