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

从嵌套数组中筛选另一嵌套数组不存在的元素

MongoDB嵌套数组元素对比与操作方案

任务1:筛选_a[]._d[].pid中不存在于_a[]._p[]的项

示例文档

{
  "_id": 123,
  "_a": [
    {
      "aid": 10,
      "_p": [
        { "pid": 1, "x": "C" },
        { "pid": 2, "x": "B" },
        { "pid": 4, "x": "A" }
      ],
      "_d": [
        { "pid": 2, "x": "M" },
        { "pid": 5, "x": "M" },
        { "pid": 7, "x": "M" }
      ]
    }
  ]
}

预期输出

{ "aid": 10, "pid": 5 }
{ "aid": 10, "pid": 7 }

聚合查询语句

db.collection.aggregate([
  { $unwind: "$_a" },
  {
    $project: {
      _id: 0,
      aid: "$_a.aid",
      unmatchedPids: {
        $filter: {
          input: "$_a._d",
          cond: { $not: { $in: ["$$this.pid", "$_a._p.pid"] } }
        }
      }
    }
  },
  { $unwind: "$unmatchedPids" },
  {
    $project: {
      aid: 1,
      pid: "$unmatchedPids.pid"
    }
  }
])

执行逻辑

  1. $unwind拆分_a数组,将每个子文档独立处理
  2. $project阶段用$filter筛选出_d中pid不在_p.pid集合内的元素
  3. 再次$unwind拆分筛选后的结果数组,将每个匹配项单独输出
  4. 最后$project只保留需要的aid和pid字段

任务2:移除_a[]._d[]中pid不存在于_a[]._p[]的对象

更新操作语句

db.collection.updateMany(
  {},
  [
    {
      $set: {
        "_a": {
          $map: {
            input: "$_a",
            as: "item",
            in: {
              aid: "$$item.aid",
              _p: "$$item._p",
              _d: {
                $filter: {
                  input: "$$item._d",
                  cond: { $in: ["$$this.pid", "$$item._p.pid"] }
                }
              }
            }
          }
        }
      }
    }
  ]
)

执行逻辑

  1. 使用聚合管道模式执行批量更新,遍历_a数组的每个子文档
  2. 对每个子文档,用$filter保留_d中pid存在于_p.pid集合内的对象
  3. 重新组装_a数组并替换原字段,完成文档更新

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 11:35:10