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

如何向MongoDB集合插入当前整月全时间维度的时序测试数据

整月时序测试数据插入实现方案

原有代码问题修复

  • 原HOURS数组存在无效值24,实际一天仅0-23共24小时,已修正
  • 原有逻辑仅生成单日数据,新增整月日期遍历逻辑
  • 补充秒级时间戳生成逻辑,满足每分钟覆盖每一秒的要求
  • 替换逐条save()为批量插入,大幅提升大数量场景下的写入性能

实现代码

const data = [
  { 'name': 'Name 10' },
  { 'name': 'Name 9' },
  { 'name': 'Name 8' },
  { 'name': 'Name 7' },
  { 'name': 'Name 6' },
  { 'name': 'Name 5' },
  { 'name': 'Name 4' },
  { 'name': 'Name 3' },
  { 'name': 'Name 2' },
  { 'name': 'Name 1' }
];

// 配置目标月份,示例为2024年11月,JS月份参数从0开始,11月对应参数10
const TARGET_YEAR = 2024;
const TARGET_MONTH = 10; 
// 获取当月总天数
const daysInMonth = new Date(TARGET_YEAR, TARGET_MONTH + 1, 0).getDate();
const HOURS = Array.from({length: 24}, (_, i) => i);
const MINUTES = Array.from({length: 60}, (_, i) => i);
const SECONDS = Array.from({length: 60}, (_, i) => i);

// 批量插入缓存数组,每10000条插入一次,可根据服务器性能调整
const insertBatch = [];
const BATCH_SIZE = 10000;

// 遍历当月每一天
for (let d = 1; d <= daysInMonth; d++) {
  // 遍历当天每小时
  for (let h = 0; h < HOURS.length; h++) {
    // 遍历当前小时每分钟
    for (let m = 0; m < MINUTES.length; m++) {
      // 遍历当前分钟每秒钟
      for (let s = 0; s < SECONDS.length; s++) {
        // 遍历所有名称项
        for (let i = 0; i < data.length; i++) {
          const timestamp = new Date(TARGET_YEAR, TARGET_MONTH, d, h, m, s).getTime();
          insertBatch.push({
            name: data[i].name,
            value: Math.floor(Math.random() * 11), // 生成0-10的随机值
            timestamp: timestamp
          });
          // 达到批量大小就执行插入
          if (insertBatch.length >= BATCH_SIZE) {
            MongoCollection.insertMany(insertBatch);
            insertBatch.length = 0;
          }
        }
      }
    }
  }
}
// 插入剩余不满批量大小的数据
if (insertBatch.length > 0) {
  MongoCollection.insertMany(insertBatch);
}

注意事项

  • 修改TARGET_YEAR和TARGET_MONTH参数即可适配其他月份,注意JS月份从0开始计数
  • 11月整月秒级数据总量为 30天 × 24小时 × 60分钟 × 60秒 × 10个名称 = 25920000条,可根据实际需求调整BATCH_SIZE避免内存溢出或写入超时
  • 如果不需要秒级数据,删除秒的循环即可,分钟级逻辑总数据量会降到432000条,写入速度会大幅提升

内容的提问来源于stack exchange,提问作者Om3ga

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 17:54:04