Loading lessons...
$out
$out
$out writes the pipeline's results into a collection. It's the stage that "materializes" your aggregation output so you can reuse it later.
$out must be last
$out can only be the final stage of a pipeline. It doesn't return documents to the caller - instead it saves them.
Example: materialize a summary
db.listingsAndReviews.aggregate([
{
$group: {
_id: "$property_type",
properties: {
$push: {
name: "$name",
accommodates: "$accommodates",
price: "$price"
}
}
}
},
{ $out: "properties_by_type" }
])
Stage 1 groups listings by property_type and uses $push to build an array of each property's details. Stage 2 ($out) writes the result into a new collection called properties_by_type.
Behavior
- Creates the target collection if it doesn't exist.
- Replaces the collection's contents if it does exist.
- Writes to a collection in the current database.
Why use $out?
- Cache the results of expensive aggregations.
- Export analysis results into a new collection.
- Build reporting tables you can query directly.
TL;DR
$outwrites pipeline results to a collection.- It must be the last stage.
- Creates the collection or replaces its contents.