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

如何使用Mongoose匹配对象数组中的值聚合MongoDB数据?

解决MongoDB聚合查询返回null的问题

问题根源

你的聚合代码返回null,核心原因是字段拼写错误:在$match阶段中使用了item字段,但你的数据里数组字段实际是items,导致没有匹配到任何文档,最终$group阶段无数据可统计,返回null。

另外,针对数组元素的单条件匹配,可简化写法,无需$elemMatch。

修正后的聚合代码

方式1:修正字段名并保留$elemMatch

model.aggregate([
  {
    $match: {
      items: { // 修正为正确的字段名items
        $elemMatch: {
          tax: { $gt: 0 }
        }
      }
    }
  },
  { $group: { _id: null, count: { $sum: 1 } } }
])

方式2:直接使用点符号匹配数组元素(更简洁)

当仅需匹配数组中存在至少一个元素满足tax > 0时,直接通过点符号即可实现,无需$elemMatch:

model.aggregate([
  {
    $match: {
      "items.tax": { $gt: 0 }
    }
  },
  { $group: { _id: null, count: { $sum: 1 } } }
])

补充说明

如果你的需求是统计所有满足tax>0的items子文档数量(而非父文档数量),可加入$unwind阶段展开数组后统计:

model.aggregate([
  { $unwind: "$items" },
  { $match: { "items.tax": { $gt: 0 } } },
  { $group: { _id: null, total_items: { $sum: 1 } } }
])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 03:20:27