$unionWith (Union)
Last updated: 2026-10-09
$unionWith (Union)
$unionWith merges the pipeline's accumulated results with documents from another collection (or the same one), optionally pre-processing that collection with a sub-pipeline. The default output is the union without deduplication. Good for combining collections into one report stream; documents with different shapes simply coexist.
| Category | Advanced & Diagnostic |
|---|---|
| MongoDB Version | 4.4+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $unionWith: { coll: "<collection>", pipeline: [ <sub-pipeline> ] } }
⚙️ Parameters
| coll | Target collection to union with. |
|---|---|
| pipeline | Optional sub-pipeline that pre-processes the target collection. |
Returns:Merged document stream from both sources
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $unionWith: merge q2 into q1, filtered
db.q1.aggregate([
{ $unionWith: { coll: 'q2', pipeline: [{ $match: { active: true } }] } }
])
Output:
// q1 results plus active q2 documents
📌 Notes
- No deduplication; identical documents may appear twice
- The sub-pipeline can $match, $project, etc. the target collection
- Different field shapes do not prevent merging
🏷️ Related Tags
💡 Related Cases
📚 Related Tutorials
❓ FAQ
QDoes $unionWith deduplicate?
ANo. It unions both sources; duplicates may appear.
QCan the sub-pipeline sort?
AYes, with regular stages other than $out, $merge, and $facet.
QCan it union the same collection twice?
AYes, point coll at the current collection for a self-union.