Single-purpose aggregation
- It is used when we need simple access to document like counting the number of documents or for finding all distinct values in a document.
- It simply provides the access to the common aggregation process using the count(), distinct() and estimatedDocumentCount() methods so due to which it lacks the flexibility and capabilities of the pipeline.
Example of Single-purpose aggregation
Let’s consider a single-purpose aggregation example where we find the total number of users in each city from the users
collection.
db.users.aggregate([
{ $group: { _id: "$city", totalUsers: { $sum: 1 } } }
])
Output:
[
{ _id: 'Los Angeles', totalUsers: 1 },
{ _id: 'New York', totalUsers: 1 },
{ _id: 'Chicago', totalUsers: 1 }
]
In this example, the aggregation pipeline first groups the documents by the city
field and then uses the $sum
accumulator to count the number of documents (users) in each city.
The result will be a list of documents, each containing the city (_id
) and the total number of users (totalUsers
) in that city.
Aggregation in MongoDB
Aggregation in MongoDB is a powerful feature that allows for complex data transformations and computations on collections of documents. It enables users to group, filter, and manipulate data to produce summarized results.
It is typically performed using the MongoDB Aggregation Pipeline which is a framework for data aggregation modeled on the concept of data processing pipelines. In this article, We will learn about Aggregation in MongoDB in detail by covering various aspects related to MongoDB Aggregation.