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

MongoDB单聚合查询:基于TicketNo实现多维度工单统计

MongoDB多维度工单聚合查询方案

假设你的工单集合名为tickets,字段包含ticketNo(工单号)、userId(用户ID)、city(城市)、store(门店)、vehicle(车辆)、status(工单状态)。以下是实现多维度汇总的聚合语句:

db.tickets.aggregate([
  // 定位指定工单所属的用户
  { $match: { ticketNo: "目标工单号" } },
  { $project: { userId: 1, _id: 0 } },
  // 关联该用户的所有工单
  {
    $lookup: {
      from: "tickets",
      localField: "userId",
      foreignField: "userId",
      as: "user_all_tickets"
    }
  },
  { $unwind: "$user_all_tickets" },
  // 标记工单活跃状态(根据实际业务定义状态范围)
  {
    $addFields: {
      "user_all_tickets.isActive": {
        $in: ["$user_all_tickets.status", ["open", "processing"]] // 替换成你的活跃状态值
      }
    }
  },
  // 按城市、门店、车辆维度统计各状态数量
  {
    $group: {
      _id: {
        city: "$user_all_tickets.city",
        store: "$user_all_tickets.store",
        vehicle: "$user_all_tickets.vehicle"
      },
      activeCount: { $sum: { $cond: ["$user_all_tickets.isActive", 1, 0] } },
      inactiveCount: { $sum: { $cond: ["$user_all_tickets.isActive", 0, 1] } }
    }
  },
  // 按城市、门店汇总(包含下属车辆的统计)
  {
    $group: {
      _id: { city: "$_id.city", store: "$_id.store" },
      vehicleStats: {
        $push: {
          vehicle: "$_id.vehicle",
          activeCount: "$activeCount",
          inactiveCount: "$inactiveCount"
        }
      },
      totalActive: { $sum: "$activeCount" },
      totalInactive: { $sum: "$inactiveCount" }
    }
  },
  // 按城市汇总(包含下属门店的统计)
  {
    $group: {
      _id: "$_id.city",
      storeStats: {
        $push: {
          store: "$_id.store",
          totalActive: "$totalActive",
          totalInactive: "$totalInactive",
          vehicleStats: "$vehicleStats"
        }
      },
      totalCityActive: { $sum: "$totalActive" },
      totalCityInactive: { $sum: "$totalInactive" }
    }
  },
  // 整理最终输出格式
  {
    $project: {
      _id: 0,
      city: "$_id",
      totalCityActive: 1,
      totalCityInactive: 1,
      storeStats: 1
    }
  }
])

关键说明:

  • 状态自定义:第3阶段的$in数组需要替换成你业务中实际的「活跃工单状态」,比如把["open", "processing"]改成系统内对应的状态值。
  • 层级汇总逻辑:通过多次$group实现从车辆→门店→城市的逐层统计,最终结果会包含每个城市的总工单量、下属各门店的统计数据,以及每个门店下各车辆的明细统计。
  • 性能优化建议:给userId和ticketNo字段创建索引,能大幅提升查询效率。

内容的提问来源于stack exchange,提问作者Virender Kumar Jangra

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 15:50:22