Aggregate In MongoDB: 4 Things (1 Min) You Must Know | Learn Aggregation Pipeline

Опубликовано: 05 Август 2026
на канале: Gokce DB
142
5

In this tutorial, you'll learn how to use the aggregate function in the MongoDB Database.


Facebook:   / gokcedbsql  

Video Transcript:

Hi guys, this is Abhi from Gokcedb. In this video, you're going to learn four ways to use the aggregate method in the MongoDB database. Number one, you wanted to calculate the count of the documents by the estate.

To do that, you can use the sum expression with the aggregate method. Here, I'm also using the group operator to group the result by state. Number two, you can also use the sum expression to calculate the total sum of properties and sizes grouped by state.

Number three min max and average expressions also work with the aggregate method. On line 9, I'm calculating the minimum property size and group the result by subdivision. On line 10, I'm calculating the maximum size by subdivision, and on line 11 I'm calculating the average size in acres and grouping the result by subdivision.

Last but not the least number four. You can use an aggregation pipeline with multiple stages. In this example, I'm first using the match operator to filter out the documents where the state is equal to New Mexico. Next, I'm using the group operator to calculate the sum of all property sizes grouped by subdivision.

Finally, I'm using the using sort operator to sort the result set by total size in descending order. There you have it. Make sure you like, subscribe, and turn on the notification bell.

Until next time.



Connect MySQL In Python:    • How To Connect To MySQL In Python (2 Min) ...  
Run Selenium PyTests In Parallel:    • How To Run Selenium PyTests In Parallel (2...  
Find_elements() in Selenium:    • How To: Find_Elements() In Selenium (3 Min...  




// 1. Use sum expression with aggregate method & group operator to count number of documents
db.gokcedb.property.find({}, {"_id": 0, "access": 0, "attributes": 0})
db.gokcedb.property.aggregate([{$group: {"_id": "$state", "count":{$sum: 1}}}])

// 2. Use sum expression with aggregate method & group to calculate the sum of property sizes in a state
db.gokcedb.property.aggregate([{$group: {"_id": "$state", "totalSize":{$sum: "$sizeInAcres"}}}])

// 3. Min, Max, Avg expressions
db.gokcedb.property.aggregate([{$group: {"_id": "$subdivision", "minSize":{$min: "$sizeInAcres"}}}])
db.gokcedb.property.aggregate([{$group: {"_id": "$subdivision", "maxSize":{$max: "$sizeInAcres"}}}])
db.gokcedb.property.aggregate([{$group: {"_id": "$subdivision", "avgSize":{$avg: "$sizeInAcres"}}}])

// 4. Aggregation pipeline with three stages: match, group, sort
db.gokcedb.property.aggregate([{$match: {state: "NM"}},
{$group: {"_id": "$subdivision", "totalSize":{$sum: "$sizeInAcres"}}},
{$sort: {totalSize: -1}}])