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

MongoDB中如何查找上报数据全为零的传感器并计算零数据占比

完全可以通过MongoDB的聚合管道实现这两个需求,注意你示例中的data字段为字符串类型,以下方案默认匹配字符串"0",如果你的实际业务中data为数值类型,将匹配条件中的"0"改为0即可。

1. 筛选所有上报数据全部为0的传感器

实现逻辑为按传感器ID分组,统计总上报量和非零数据上报量,过滤出非零上报量为0的传感器即可:

db.你的集合名.aggregate([
  // 按传感器ID分组统计核心指标
  {
    $group: {
      _id: "$sensor",
      totalReport: { $sum: 1 },
      nonZeroReport: {
        $sum: {
          $cond: [{ $ne: ["$data", "0"] }, 1, 0]
        }
      }
    }
  },
  // 过滤出所有上报都是0的传感器
  {
    $match: {
      nonZeroReport: 0
    }
  },
  // 调整输出字段格式,可选
  {
    $project: {
      sensorId: "$_id",
      totalReportCount: "$totalReport",
      _id: 0
    }
  }
])

2. 统计每台传感器零值数据占总上报量的比例

实现逻辑为按传感器ID分组,统计总上报量和零值上报量,再计算二者的比值即可:

db.你的集合名.aggregate([
  {
    $group: {
      _id: "$sensor",
      totalReport: { $sum: 1 },
      zeroReport: {
        $sum: {
          $cond: [{ $eq: ["$data", "0"] }, 1, 0]
        }
      }
    }
  },
  // 计算零值占比,这里保留2位小数,可按需调整精度
  {
    $project: {
      sensorId: "$_id",
      totalReportCount: "$totalReport",
      zeroReportCount: "$zeroReport",
      zeroRatio: {
        $round: [ { $divide: ["$zeroReport", "$totalReport"] }, 2 ]
      },
      _id: 0
    }
  },
  // 可选:按零值占比从高到低排序
  {
    $sort: { zeroRatio: -1 }
  }
])

扩展说明

如果需要统计指定时间范围内的数据,可以在聚合管道的最开头添加$match阶段过滤time字段,示例如下:

{
  $match: {
    time: {
      $gte: ISODate("2021-09-01T00:00:00+08:00"),
      $lt: ISODate("2021-10-01T00:00:00+08:00")
    }
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 14:39:02