All about MongoDB Aggregation and queries

Muttineni Sai Rohith
CodeX
Published in
4 min readMar 3, 2024

--

MongoDB Aggregation Framework is a powerful set of tools for processing and transforming documents in a collection. It allows us to perform various data manipulations, aggregations, and transformations, akin to SQL GROUP BY and JOIN operations. Here’s an overview of some key aggregation queries in MongoDB:

1. Match Documents:

Use $match to filter documents based on specified criteria — Similar to where command.

db.your_collection_name.aggregate([
{ $match: { key: "value" } }
])

2. Group Documents:

Use $group to group documents based on a specified key and perform aggregations within each group.

db.your_collection_name.aggregate([
{ $group: { _id: "$key", count: { $sum: 1 } } }
])

3. Project Fields:

Use $project to reshape documents, and include or exclude fields — Similar to the select command in RDBMS.

db.your_collection_name.aggregate([
{ $project: { newKey: "$existingKey", _id: 0 } }
])

4. Sort Documents:

Use $sort to sort documents based on specified fields.

db.your_collection_name.aggregate([
{ $sort: { key: 1 } }
])

5. Limit Results:

Use $limit to limit the number of documents in the output.

db.your_collection_nam…

--

--

Muttineni Sai Rohith
CodeX

Senior Data Engineer with experience in Python, Pyspark and SQL! Reach me at sairohith.muttineni@gmail.com