$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.

CategoryAdvanced & Diagnostic
MongoDB Version4.4+
Example Languagemongosh (Shell)

📝 Syntax

{ $unionWith: { coll: "<collection>", pipeline: [ <sub-pipeline> ] } }

⚙️ Parameters

collTarget collection to union with.
pipelineOptional 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

📚 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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏