Combine 2 pipelines together with UnionWith Possible?

Hello,

Is there a way to link 2 different pipeline together through operator $unionWith?

I don’t see how I can reference the second pipeline in the first one:
$unionWidth stage in first pipeline
{
coll: “”,
pipeline: my second pipeline or other stages???
}

Hi and welcome!

$unionWith literally blends the documents from two different collections into the aggregation pipeline. As such, it doesn’t link the documents together or attempt to relate them.

The coll field should be the name of the collection where your documents should be extracted.

The pipeline field should be an array of aggregation stages. $unionWith uses the pipeline array directly, you don’t refer to a pipeline by name (because MongoDB doesn’t persist pipelines in the database).

So if I have an aggregation on the customers collection and I want to merge documents from the accounts collection, I might create a $unionWith stage like this:

{
    coll: "accounts",
    pipeline: [],
}

That’s an empty pipeline so no changes will be made and all the documents will be merged into the pipeline. If you browse the results, remember to dig far enough in so you can see the different documents from the other collection appear in your pipeline results.

If you want the pipeline to do processing (for example, matching documents or projecting fields) you can add aggregation stages inside the [ ] - for example:

      pipeline: [ { $match: { "limit" : NumberInt(10000) } } ], 

Would only use documents from accounts where the limit field was 10000. You could use $project to select fields. If you’ve created a pipeline in another aggregation tab, go to the Query Code section and you should see the pipeline array you want as the first parameter of the aggregate method.