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

如何在MongoDB中分别统计对象内不同数组的元素数量?

解决MongoDB统计嵌套数组元素总数的问题

错误原因分析

你遇到的错误是因为$size引用的字段路径错误:$cars无法定位到目标数组,实际cars嵌套在customer_vehicles对象下,正确路径应为$customer_vehicles.cars。同时你的$group分组依据$customer_vehicles.cars也不符合需求——这会把每个不同的cars数组作为分组键,无法统计总数量。

正确实现方案

统计整个集合中cars和bikes的总元素数量

如果需要统计所有文档里cars和bikes的元素总数,可通过以下聚合查询实现:

db.customer_vehicle_details.aggregate([
  // 先计算每个文档中cars和bikes的元素数量
  {
    $project: {
      cars_count: { $size: "$customer_vehicles.cars" },
      bikes_count: { $size: "$customer_vehicles.bikes" }
    }
  },
  // 对所有文档的数量求和
  {
    $group: {
      _id: null, // 不按字段分组,统计全局总和
      total_cars: { $sum: "$cars_count" },
      total_bikes: { $sum: "$bikes_count" }
    }
  }
])

按用户(customer_id)统计各自的cars和bikes数量

如果需要按每个用户分别统计,只需调整$group的分组键为customer_id:

db.customer_vehicle_details.aggregate([
  {
    $project: {
      customer_id: 1,
      cars_count: { $size: "$customer_vehicles.cars" },
      bikes_count: { $size: "$customer_vehicles.bikes" }
    }
  },
  {
    $group: {
      _id: "$customer_id",
      total_cars: { $sum: "$cars_count" },
      total_bikes: { $sum: "$bikes_count" }
    }
  }
])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 09:01:08