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 dynamicimportant_partobject 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$filterensures we only keep actual arrays, in case some fields inimportant_partaren'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_partare arrays, you can skip the$filterstep to simplify the pipeline. - MongoDB 3.4 introduced both
$objectToArrayand$reduce, so this pipeline is fully compatible with your version.
内容的提问来源于stack exchange,提问作者grunci
相关产品推荐
相关产品推荐

