Aggregate operation on MongoDB
MongoDB Aggregate Operation
MongoDB is a NoSQL database that allows us to store and manipulate the unstructured data. MongoDB stores the data as bson document formate.
One of the key features of MongoDB is it can perform aggregate
operations on the documents of multiple collections.
Aggregate operations are used to perform operations on a collection of documents and return the results as a single document.
Aggregation Pipelines
Aggregation pipeline can consists of one or more stages that process the documents. aggregate()
method is used on MongoDB for performe aggregate operations .
The aggregate()
method takes an array of stages as input, Each stage represents a specific operation to be performed on the collection of documents. All stages of inputs are executed in sequence, with the output of one stage being passed to the next stage as input.
We can use number of different stages for aggregate
operations in MongoDB based on the query requirement. Below are a few common aggregate operations that can be performed using MongoDB:
Grouping Documents
The $group
stage allows us to group documents based on a specific field or set of fields. We can use the $group
stage to calculate aggregated values such as the sum, average, minimum, or maximum of a field for all the documents in a group.
For example, the following aggregation operation groups documents in a collection by the brand field and calculates the total count of products in each brand:
db.products.aggregate([
{ $group: { _id: "$brand", count: { $sum: 1 } } }
]);
Filtering Documents
The $match
stage allows us to filter documents based on specific criteria. W can use the $match
stage to select only documents which meet certain criteria.
For example, the following aggregation operation filters documents in a collection where the price
field is greater than 50
db.products.aggregate([
{ $match: { price: { $gt: 50} } }
]);
Sorting Documents
The $sort
stage allows us to sort documents based on one or more fields. We can use the $sort
stage to sort documents in ascending (1) or descending (-1) order.
For example, the following aggregation operation sorts documents in a collection by the price field in descending order. -1 refers for descending order
db.products.aggregate([
{ $sort: { price: -1 } }
]);
Projecting Documents
The $project
stage allows us to select only specific fields from a document and create new fields with calculated values. We can use the $project
stage to reshape documents and include only the fields which are relevant to us.
For example, the following aggregation operation selects only the name
, price
, and brand
fields from a documents of products collection and creates a new field called discount_price
:
db.products.aggregate([
{ $project: { name: 1,
price: 1,
brand: 1,
discount_price: { $subtract: ["$price", 10] }
}
}
]);
0 Comments
Leave a reply
Your email address will be private. Required fields are marked with *