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

MongoDB 3.4聚合框架实现对象内所有数组合并求并集

Solution for Dynamic Array Union in MongoDB 3.4 Aggregation

Got it, let's figure out how to get the union of all dynamic arrays inside your important_part object in MongoDB 3.4. Since the fields are dynamic, we can't hardcode them into $setUnion directly—but we have two key operators introduced in 3.4 that make this possible: $objectToArray and $reduce.

Let's start with example data

First, let's assume your input document looks something like this (adjust based on your actual data):

{
  "_id": 1,
  "important_part": {
    "user_tags": ["admin", "editor"],
    "project_tags": ["editor", "viewer"],
    "team_tags": ["viewer", "guest"]
  }
}

And your desired output is the union of all these arrays:

{
  "_id": 1,
  "all_tags_union": ["admin", "editor", "viewer", "guest"]
}

The Aggregation Pipeline

Here's the pipeline that will get you there:

db.your_collection.aggregate([
  // Step 1: Convert the dynamic object into an array of key-value pairs
  {
    $project: {
      key_value_pairs: { $objectToArray: "$important_part" }
    }
  },
  // Step 2: Extract only the array values (ignore keys)
  {
    $project: {
      arrays_list: {
        // Optional: Filter out any non-array values if needed
        $filter: {
          input: "$key_value_pairs.v",
          as: "item",
          cond: { $isArray: "$$item" }
        }
      }
    }
  },
  // Step 3: Use $reduce to iteratively compute the union of all arrays
  {
    $project: {
      all_tags_union: {
        $reduce: {
          input: "$arrays_list",
          initialValue: [],
          in: { $setUnion: ["$$value", "$$this"] }
        }
      }
    }
  }
])

How it works

Let's break down each step:

  • $objectToArray: This converts your dynamic important_part object into an array of {k: "field_name", v: [array_value]} objects. This lets us handle any number of dynamic fields without hardcoding their names.
  • Extract & Filter Arrays: We pull out just the v (value) field from each key-value pair. The optional $filter ensures we only keep actual arrays, in case some fields in important_part aren't arrays.
  • $reduce + $setUnion: We iterate over the list of arrays. For each array, we compute the union with the accumulated result (starting with an empty array). This builds up the full union of all arrays, automatically removing duplicates.

Notes

  • If you're sure all fields in important_part are arrays, you can skip the $filter step to simplify the pipeline.
  • MongoDB 3.4 introduced both $objectToArray and $reduce, so this pipeline is fully compatible with your version.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 08:28:02