Learning MongoDB

0% completed

Previous
Next
MongoDB Aggregation $out

The $out stage in MongoDB's aggregation framework is used to write the resulting documents of the aggregation pipeline to a specified collection. This stage is particularly useful when you want to save the results of an aggregation operation for further use or analysis. It can replace the contents of an existing collection or create a new one if it does not already exist.

Syntax

{ $out: "<collection>" }
  • $out: The operator used to specify the output stage.
  • collection: The name of the collection where the results should be written.

Example Setup

First, let's insert some documents into the sales collection to work with:

db.sales.insertMany([ { item: "apple", quantity: 10, price: 1, date: new Date("2023-01-01") }, { item: "banana", quantity: 5, price: 1, date: new Date("2023-01-02") }, { item: "orange", quantity: 8, price: 1.5, date: new Date("2023-01-03") }, { item: "apple", quantity: 15, price: 1, date: new Date("2023-01-04") }, { item: "banana", quantity: 7, price: 1, date: new Date("2023-01-05") } ])

Example 1: Basic Usage of $out

Write the results of an aggregation pipeline to a new collection called fruit_summary.

Pipeline:

db.sales.aggregate([ { $match: { item: "apple" } }, { $group: { _id: "$item", totalQuantity: { $sum: "$quantity" } } }, { $out: "fruit_summary" } ])

Explanation:

  • $match: Filters the documents to include only those where the item is "apple".
  • $group: Groups the documents by the item field and calculates the total quantity of apples.
  • $out: Writes the results to the fruit_summary collection.

This command results in a new collection fruit_summary with a document that looks like this:

{ "_id": "apple", "totalQuantity": 25 }

Example 2: Advanced Usage with Multiple Stages

Create a summary collection sales_summary that includes the total sales and average price for each item.

Pipeline:

db.sales.aggregate([ { $group: { _id: "$item", totalSales: { $sum: { $multiply: ["$quantity", "$price"] } }, avgPrice: { $avg: "$price" } } }, { $out: "sales_summary" } ])

Explanation:

  • $group: Groups the documents by the item field. For each item, it calculates:
    • totalSales: The sum of the product of quantity and price.
    • avgPrice: The average price.
  • $out: Writes the results to the sales_summary collection.

This command results in a new collection sales_summary with documents like:

{ "_id": "apple", "totalSales": 25, "avgPrice": 1 } { "_id": "banana", "totalSales": 12, "avgPrice": 1 } { "_id": "orange", "totalSales": 12, "avgPrice": 1.5 }

Example 3: Using $out with Date Aggregations

Create a collection daily_sales that includes the total quantity sold for each day.

Pipeline:

db.sales.aggregate([ { $group: { _id: { day: { $dayOfMonth: "$date" }, month: { $month: "$date" }, year: { $year: "$date" } }, totalQuantity: { $sum: "$quantity" } } }, { $out: "daily_sales" } ])

Explanation:

  • $group: Groups the documents by day, month, and year. For each group, it calculates the total quantity sold.
  • $out: Writes the results to the daily_sales collection.

This command results in a new collection daily_sales with documents like:

{ "_id": { "day": 1, "month": 1, "year": 2023 }, "totalQuantity": 10 } { "_id": { "day": 2, "month": 1, "year": 2023 }, "totalQuantity": 5 } { "_id": { "day": 3, "month": 1, "year": 2023 }, "totalQuantity": 8 } { "_id": { "day": 4, "month": 1, "year": 2023 }, "totalQuantity": 15 } { "_id": { "day": 5, "month": 1, "year": 2023 }, "totalQuantity": 7 }

Use Cases

  • Data Export: Export the results of an aggregation to a new collection for reporting purposes.
  • Backup: Create a backup of the processed data.
  • Transformation: Store transformed data into a different collection for subsequent queries.

The $out stage is a powerful tool in MongoDB's aggregation framework that allows you to store the results of your data processing workflows. By understanding how to use the $out stage effectively, you can save the results of complex aggregations for further analysis, reporting, and archiving.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next