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

如何用MongoDB查询筛选子文档数组并移除指定userId项?

MongoDB查询移除嵌套数组指定元素并返回完整文档

可以用MongoDB的聚合管道实现这个需求,核心是通过$map和$filter操作符处理嵌套数组,同时保留文档的所有原有字段。

聚合查询代码

db.collection.aggregate([
  {
    $addFields: {
      users: {
        $map: {
          input: "$users",
          as: "user",
          in: {
            ..."$$user",
            userInteractions: {
              $filter: {
                input: "$$user.userInteractions",
                as: "interaction",
                cond: { $ne: ["$$interaction.userId.$oid", "633eb753c8e3d3fd71d1c254"] }
              }
            }
          }
        }
      }
    }
  }
])

代码说明

  • $addFields:替换users字段的同时,自动保留文档中其他字段(如_id、email)
  • $map:遍历users数组,对每个用户对象进行处理
  • $filter:在每个用户的userInteractions数组中,筛选出userId.$oid不等于目标ID的元素,从而移除指定的交互记录

示例文档

{
  "_id": {
    "$oid": "633c25965034208db76cfb1e"
  },
  "email": "test@test.com",
  "users": [
    {
      "type": "person",   
      "isActive": true,
      "userInteractions": [
        {
          "userId": {
            "$oid": "633eb753c8e3d3fd71d1c254"
          },
          "firstName": "Tom",
          "lastName": "Hawkins"
        },
        {
          "userId": {
            "$oid": "633eb753c8e3d3fd71d1c222"
          },
          "firstName": "Melan",
          "lastName": "Key"
        },
        {
          "userId": {
            "$oid": "633eb753c8e3d3fd71d1c259"
          },
          "firstName": "Ken",
          "lastName": "Olibar"
        }
      ]
    }
  ]
}

预期输出

{
  "_id": {
    "$oid": "633c25965034208db76cfb1e"
  },
  "email": "test@test.com",
  "users": [
    {
      "type": "person",   
      "isActive": true,
      "userInteractions": [
        {
          "userId": {
            "$oid": "633eb753c8e3d3fd71d1c222"
          },
          "firstName": "Melan",
          "lastName": "Key"
        },
        {
          "userId": {
            "$oid": "633eb753c8e3d3fd71d1c259"
          },
          "firstName": "Ken",
          "lastName": "Olibar"
        }
      ]
    }
  ]
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 16:01:36