> For the complete MongoDB documentation index, see www.mongodb.com/docs/llms.txt

# Aggregation Pipeline and Sharded Collections

The aggregation pipeline supports operations on [sharded](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-sharded-cluster) collections. This section describes behaviors specific to the [aggregation pipeline](https://www.mongodb.com/docs/manual/core/aggregation-pipeline.md#std-label-aggregation-pipeline) and sharded collections.

## Behavior

If the pipeline starts with an exact [`$match`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/match.md#mongodb-pipeline-pipe.-match) on a [shard key](https://www.mongodb.com/docs/manual/reference/glossary.md#std-term-shard-key), and the pipeline does not contain [`$out`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/out.md#mongodb-pipeline-pipe.-out) or [`$lookup`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/lookup.md#mongodb-pipeline-pipe.-lookup) stages, the entire pipeline runs on the matching shard only.

When aggregation operations run on multiple shards, the results are routed to the [`mongos`](https://www.mongodb.com/docs/manual/reference/program/mongos.md#mongodb-binary-bin.mongos) to be merged, except in the following cases:

- If the pipeline includes the [`$out`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/out.md#mongodb-pipeline-pipe.-out) stage, the merge runs on the shard where the output collection lives.

- If the pipeline includes the [`$lookup`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/lookup.md#mongodb-pipeline-pipe.-lookup) stage that references an unsharded collection, the merge runs on the shard where the unsharded collection lives.

- If the pipeline includes a sorting or grouping stage, and the [allowDiskUse](https://www.mongodb.com/docs/manual/reference/command/aggregate.md#std-label-aggregate-cmd-allowDiskUse) setting is enabled, the merge runs on a randomly-selected shard.

## Optimization

When splitting the aggregation pipeline into two parts, the pipeline is split to ensure that the shards perform as many stages as possible with consideration for optimization.

To see how the pipeline was split, include the [`explain`](https://www.mongodb.com/docs/manual/reference/method/db.collection.aggregate.md#mongodb-method-db.collection.aggregate) option in the [`db.collection.aggregate()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.aggregate.md#mongodb-method-db.collection.aggregate) method.

Optimizations are subject to change between releases.
