Skip to main content

馃Ω Saving to a Collection

You can export the result of an aggregation pipeline to a different DB/collection. To do that, just add a last aggregation stage to your pipeline:

Run this from the source collection

[{ $out: { db: "<output-db>", coll: "<output-collection>" } }]

You can omit the db attribute, and the new collection will be created in the current DB.

{ $out: "<output-collection>" }

馃憪 Create a copy of the books with exactly 100 pages and output as a new collection named OneHundredPagesBooks.

Answer
[
{$match: {pages: 100}},
{$out: "OneHundredPagesBooks"}
]

After running this, we should see a new collection with:

show collections