MongoDB Aggregation $project
Introduction
The $project
stage in MongoDB's aggregation framework is used to reshape documents in the pipeline by including, excluding, or adding fields. This stage allows you to control the output of your aggregation results, making it a powerful tool for data transformation.
Prerequisites
MongoDB installed and running on your machine.
Access to
mongosh
and a populated database 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
Let’s assume you have a collection named sales
with documents that look like this:
Step 4: Using $project
$project
1. Basic Usage of $project
$project
To include specific fields in the output documents, you can use the $project
stage. For example, if you only want to display the item
and quantity
fields:
Output:
2. Excluding Fields
You can also exclude specific fields from the output. For example, to exclude the price
field:
Output:
3. Adding Computed Fields
You can also create new fields based on existing fields. For instance, if you want to calculate the total price for each item (quantity * price), you can do so like this:
Output:
4. Reshaping Document Structure
You can change the structure of your documents. For example, to create a new document structure that groups item details:
Output:
Conclusion
You have learned how to use the $project
stage in MongoDB's aggregation framework to reshape documents by including, excluding, or adding fields. This stage is essential for transforming your data into the desired format for analysis or reporting.
Feel free to reach out if you have any questions or need further guidance!
Last updated