0% found this document useful (0 votes)
31 views7 pages

24 - Aggregation

MongoDB aggregation pipelines allow users to process and transform document data through a series of stages similar to an assembly line. The $match stage filters documents, the $project stage changes fields, and the $group stage groups documents to find ratios or other aggregations, producing a single output document. Pipelines use the db.collection.aggregate() method and processes data in a similar way to SQL grouping and aggregation.

Uploaded by

k.nitin.r
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views7 pages

24 - Aggregation

MongoDB aggregation pipelines allow users to process and transform document data through a series of stages similar to an assembly line. The $match stage filters documents, the $project stage changes fields, and the $group stage groups documents to find ratios or other aggregations, producing a single output document. Pipelines use the db.collection.aggregate() method and processes data in a similar way to SQL grouping and aggregation.

Uploaded by

k.nitin.r
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

MongoDB Aggregation Pipelines

COSC 061 - Fall 2022 - Dartmouth College


Pipelines
Think “Assembly line”
$match $project $group
3
2

$match lters out $project turns $group nds the ratio of red
the green shapes squares into to blue circles (documents)
circles and produces a single
document containing that
ratio.
fi
fi
Aggregate form array

db.collection.aggregate([ { stage 1}, { stage 2}, {... state N} ], {options})


SQL Example
make model cc priceNew
SELECT make, COUNT(*) as numModels
FROM dirtBikes
Yamaha TTR50 50 1500
GROUP BY model;
Yamaha TTR110 110 2100

Honda CRF50F 50 1500

Honda CRF125 125 2999


make numModels Honda CRF125BW 125 3399
Yamaha 2 Kawasaki KX65 65 3700
Honda 3

Kawasaki 1
MongoDB Aggregate

db.dirtBikes.aggregate([{
$group: {
"_id": "$make",
"num_models": {
$sum: 1
}
}
}])
MongoDB Aggregate

db.dirtBikes.aggregate([{
$match: {
"priceNew" : {$gt : 2700 }
}
},{
$group: {
"_id": "$make",
"num_models": {
$sum: 1
},
"avgCost": {
$avg: "$priceNew"
}
}
}])
stage action Doc mapping

selects values from the documents, even


$project 1:1
deep inside.

$match filter n:1

$group aggregation, like sum, COUNT n:1

$sort sorting 1:1

$skip skips results n:1

$limit limit the results n:1

$unwind flatten or denormalize the data 1:n

redirect output to a collection instead


$out 1:1
of a cursor

limits documemts based on access m:n,


$redact
permission info m >= n

m:n,
$geonear limits documemts based on location info
m >= n

You might also like