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

MongoDB文档中如何筛选对象数组内的活跃元素

解决MongoDB数组元素过滤问题

你的现有查询仅完成了文档筛选,$match阶段只会找出包含history.active: true元素的用户文档,但不会对history数组内部的元素做过滤,所以数组里的所有条目都会被保留,这就是你没得到预期结果的原因。

要实现只保留history数组中active: true的记录,需要在聚合管道里加上数组过滤步骤,推荐用$addFields(或$project)配合$filter操作符,具体查询如下:

db.getCollection('users').aggregate([
  // 先精准定位目标用户
  { $match: { 'name': 'Test User' } },
  // 过滤history数组,仅保留active为true的元素
  {
    $addFields: {
      history: {
        $filter: {
          input: "$history",
          cond: { $eq: ["$$this.active", true] }
        }
      }
    }
  }
])

代码说明

  • $match:先定位到目标用户,减少后续处理的数据量
  • $addFields:替换原有的history字段(因字段已存在,会直接覆盖)
  • $filter:遍历history数组,只保留满足cond条件的元素,$$this代表数组当前遍历的元素

如果你的MongoDB版本较低(低于3.2),也可以用$unwind+$match+$group的方式实现,但性能不如$filter,示例如下:

db.getCollection('users').aggregate([
  { $match: { 'name': 'Test User' } },
  { $unwind: "$history" },
  { $match: { "history.active": true } },
  {
    $group: {
      _id: "$_id",
      name: { $first: "$name" },
      createDate: { $first: "$createDate" },
      history: { $push: "$history" },
      updateDate: { $first: "$updateDate" }
    }
  }
])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 23:24:30