- Install MongoDB
- Install Node.js
- Install MongoDB Compass (optional, for GUI-based database management)
- Clone the repository:
git clone <your-repo-url> cd mongodb-aggregation-practice
- Install dependencies:
npm install
- Start MongoDB server (if not running):
mongod --dbpath=/path/to/your/data
- Run the script to insert sample data:
node seed.js
- Start practicing aggregation queries in
practice.js.
| Stage | Description |
|---|---|
$match |
Filters documents based on conditions (like WHERE in SQL). |
$group |
Groups documents by a field and performs aggregations (sum, count, etc.). |
$project |
Shapes documents by including/excluding fields. |
$sort |
Sorts the documents in ascending or descending order. |
$limit |
Limits the number of output documents. |
$skip |
Skips a specified number of documents. |
$unwind |
Deconstructs an array field into multiple documents. |
$lookup |
Performs a left join with another collection. |
$addFields |
Adds new fields to documents. |
$set |
Alias for $addFields (MongoDB 4.2+). |
$replaceRoot |
Replaces the document root with a specified field. |
$facet |
Performs multiple aggregation pipelines in a single query. |
$bucket |
Categorizes documents into groups based on a range. |
$out |
Writes the aggregation results to a new collection. |
$merge |
Merges results into an existing collection. |
$count |
Returns the count of documents processed in the pipeline. |
Write and test your aggregation queries in practice.js. Example: