Aggregating data with MongoDB
Sometimes, we do not just want to simply retrieve data from the database, but instead, we want to create some statistics from the data by combining and summarizing it. This process is called data aggregation, and it can help us understand more about the data. For example, we can count the total number of views per post, get the number of daily views per post, or calculate the average session duration when viewing a post.
MongoDB supports a special aggregation syntax using the .aggregate()
function on a collection. Using this aggregation functionality from MongoDB allows us to efficiently query and process documents. The operations it provides are similar to what can be done with Structured Query Language (SQL) queries. Mainly, we are going to use the following aggregation operations:
$match
: Used to filter documents$group
: Used to group documents by a certain property$project
: Used to map properties to different properties, or process...