In MongoDB, you can use the aggregation framework to perform aggregate functions. The aggregation framework allows you to process data records and return computed results. Here are some commonly used aggregate functions in MongoDB:
1. sum: Calculates the sum of numeric values in a group.
db.collection.aggregate([
{ group: { _id: null, total: { sum: "field_name" } } }
])
2. avg: Calculates the average of numeric values in a group.
db.collection.aggregate([
{ group: { _id: null, average: { avg: "field_name" } } }
])
3. min: Returns the minimum value in a group.
db.collection.aggregate([
{ group: { _id: null, min: { min: "field_name" } } }
])
4. max: Returns the maximum value in a group.
db.collection.aggregate([
{ group: { _id: null, max: { max: "field_name" } } }
])
5. count: Counts the number of documents in a collection.
db.collection.aggregate([
{ count: "total_documents" }
])
6. group: Groups documents by a specified expression and applies aggregate functions.
db.collection.aggregate([
{ group: { _id: "group_field", count: { sum: 1 } } }
])
7. match: Filters documents to pass only those that match a specified condition.
db.collection.aggregate([
{ match: { field_name: { gte: 100 } } },
{ group: { _id: null, total: { sum: "field_name" } } }
])
8. project: Reshapes documents by including, excluding, or adding fields.
db.collection.aggregate([
{ project: { _id: 0, new_field: "field_name" } }
])
These aggregate functions are part of the MongoDB aggregation pipeline and are used within the `aggregate` method to process data and return computed results.
No comments:
Post a Comment