MongoDB Aggregation $out
Introduction
The $out
stage in MongoDB's aggregation framework is used to write the results of an aggregation pipeline to a new collection. This stage effectively creates a new collection (or replaces an existing one) with the documents generated by the pipeline, making it useful for storing aggregated results for further analysis or reporting.
Prerequisites
MongoDB installed and running on your machine.
Access to
mongosh
and a populated collection with sample data.
Step 1: Start mongosh
mongosh
Open Terminal/Command Prompt:
Launch your terminal (macOS/Linux) or command prompt (Windows).
Start
mongosh
:Type the following command and press Enter:
Step 2: Switch to the Database
Switch to the database where your collection is located.
Use a Database:
Step 3: Sample Data
Assume you have a collection named sales
with documents that look like this:
Step 4: Using $out
$out
1. Basic Usage of $out
$out
To create a new collection called totalSales
that contains the total revenue for each item, you can use the following aggregation pipeline:
Note: If the totalSales
collection already exists, it will be replaced by the new data.
2. Verify the Output
To check the contents of the newly created totalSales
collection, you can use the following command:
Output:
3. Using $out
After Filtering
$out
After FilteringYou can also use $out
after applying various stages in the aggregation pipeline. For example, if you want to filter items based on quantity before calculating the total revenue:
4. Combining $out
with Other Stages
$out
with Other StagesYou can combine $out
with various stages to create more complex aggregations. For instance, if you want to group items by category and then output the results:
Assuming you have a products
collection with a category
field:
products collection:
You can create a new collection that summarizes total revenue by category:
Conclusion
You have learned how to use the $out
stage in MongoDB's aggregation framework to write the results of an aggregation pipeline to a new or existing collection. This stage is beneficial for storing processed data for future queries and analyses.
Feel free to reach out if you have any questions or need further guidance!
Last updated