All about MongoDB Aggregation and queries
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…