In MongoDB, aggregation pipeline operators are used to perform various operations on documents as they pass through the stages of an aggregation pipeline. Here are some common aggregation pipeline operators:
1. $match
Filters documents based on specified criteria.
2. $group
Groups documents by a specified key and allows for aggregation operations like sum, average, count, etc.
3. $project
Reshapes each document, allowing you to include, exclude, or add new fields.
4. $sort
Sorts the documents based on specified fields.
5. $limit
Limits the number of documents passed to the next stage.
6. $skip
Skips a specified number of documents.
7. $unwind
Deconstructs an array field from the input documents to output a document for each element.
8. $lookup
Performs a left outer join to another collection in the same database.
9. $addFields
Adds new fields to documents or modifies existing fields.
10. $replaceRoot
Replaces a document with the specified embedded document.
11. $count
Counts the number of documents that pass through the pipeline.
12. $facet
Processes multiple aggregation pipelines within a single stage on the same set of input documents.
13. $bucket
Categorizes documents into groups based on a specified range of values.
14. $geoNear
Returns documents sorted by distance from a specified point.
Example of Using Operators:
db.collection.aggregate([
{ $match: { status: "active" } }, // Filter active documents
{ $group: { _id: "$category", total: { $sum: "$amount" } } }, // Group by category and sum amounts
{ $sort: { total: -1 } }, // Sort by total in descending order
{ $limit: 5 } // Limit to top 5 results
]);
These operators allow for powerful data manipulation and analysis within MongoDB, enabling complex queries and transformations.
