05 - MongoDB Aggregation Flashcards
Syntax when using pipeline
collection = "tweets" pipeline = [$stage1, $stage2, ...$stageN] db.<COLLECTION>.aggregate( pipeline, { options } )
$match
Similar to find()
$project
Shape documents
$sort
Like the cursor method of the same name
Define & list
$group
LIst - 4
Used to aggregate field values from multiple documents
$sum
$avg
$min
$max
$limit
Used to limit the amount of documents returned
$unwind
Separates documents with arrays
$out
Specifies an output collection
Similar to find()
$match
Shape documents
$project
Like the cursor method of the same name
$sort
Used to aggregate field values from multiple documents
$sum
$avg
$min
$max
Define & list
$group
LIst - 4
Used to limit the amount of documents returned
$limit
Separates documents with arrays
$unwind
Specifies an output collection
$out
Code
Count number of action movies (with $count)
db.moviesSmall.aggregate([{"$match" : {"category" : "action"}}, {"$count" : "movies"}])
Find the rating of the highest rated expensive movie
(aggregate)
budget
imdb_rating
`db.moviesSmall.aggregate([{
“$match” : {“budget” : {“$gt” : 25}}},
{“$group” : {“_id” : “movies”,
“highest” : {“$max” : “$imdb_rating”}}}])`
Get class with the most number of students
db.grades.aggregate([{"$group" : {"_id" : "$class_id", "num_students" : {"$sum" : 1}}}, {"$group" : {"_id" : 1, "most" : { "$max" : "$num_students"}}}])
Get class with the most number of students (sort)
aggregate
class_id
num_students
db.grades.aggregate([{"$group" : {"_id" : "$class_id", "num_students" : {"$sum" : 1}}}, { "$sort" : {"num_students" : -1}}, { "$limit" : 1}])