馃Ω 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:
- Atlas UI
- MongoDB Shell
Run this from the source collection
[{ $out: { db: "<output-db>", coll: "<output-collection>" } }]
db.sourceCollection.aggregate[{ $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
- Atlas UI
- MongoDB Shell
[
{$match: {pages: 100}},
{$out: "OneHundredPagesBooks"}
]
let oneHundredPagesBooks = {$match: {pages: 100}};
let saveToNewCollection = {$out: "OneHundredPagesBooks"}
db.books.aggregate([
oneHundredPagesBooks,
saveToNewCollection
]);
After running this, we should see a new collection with:
show collections