Mongodb - Cheat Sheet Page 3

ADVERTISEMENT

More information can be found from the MongoDB Tutorial
MongoDB - Cheat Sheet
@
th
Version 1.0 / 27
December 2012 / Page 3 of 4
Pipeline Stages
Comparison with SQL
$project
Change the set of documents by modifying keys and values. This is a 1:1 mapping.
WHERE
$match
$match
This is a filtering operation and thus this can reduce the amount of documents that are given as input to the
GROUP BY
$group
next stage. This can be used for example if aggregation should only happen on a subset of the data.
A
$group
This does the actual aggregation and as we are grouping by one or more keys this can have a reducing effect
HAVING
$match
G
on the amount of documents.
SELECT
$project
$sort
Sorting the documents one way or the other for the next stage. It should be noted that this might use a lot of
G
memory. Thus if possible one should always try to reduce the amount of documents first.
ORDER BY
$sort
R
$skip
With this it is possible to skip forward in the list of documents for a given amount of documents. This allows
LIMIT
$limit
E
for example starting only from the 10th document. Typically this will be used together with “$sort” and
SUM
$sum
especially together with “$limit”.
G
$limit
This limits the amount of documents to look at by the given number starting from the current position.
COUNT
$sum
A
$unwind This is used to unwind document that are using arrays. When using an array the data is kind of pre-joined and
JOIN
$unwind
this operation will be undone with this to have individual documents again. Thus with this stage we will
T
increase the amount of documents for the next stage.
I
Aggregation Examples
O
Counts the number of ships per operator, would be in SQL:
db.ships.aggregate([{$group : {_id : "$operator", num_ships :
N
SELECT operator, count(*) FROM ships GROUP BY operator;
{$sum : 1}}}])
Combination of $project-stage and $group-stage.
db.ships.aggregate([{$project : {_id : 0, operator : {$toLower
F
: "$operator"}, crew : {"$multiply" : ["$crew",10]}}}])
R
Aggregation Expressions
A
$sum
Summing up values
db.ships.aggregate([{$group : {_id : "$operator", num_ships : {$sum : "$crew"}}}])
M
$avg
Calculating average values
db.ships.aggregate([{$group : {_id : "$operator", num_ships : {$avg : "$crew"}}}])
E
$min / $max
Finding min/max values
db.ships.aggregate([{$group : {_id : "$operator", num_ships : {$min : "$crew"}}}])
$push
Pushing values to a result
db.ships.aggregate([{$group : {_id : "$operator", classes : {$push: "$class"}}}])
W
array
O
$addToSet
Pushing values to a result
db.ships.aggregate([{$group : {_id : "$operator", classes : {$addToSet :
"$class"}}}])
array without duplicates
R
$first / $last
Getting the first / last
db.ships.aggregate([{$group : {_id : "$operator", last_class : {$last :
K
"$class"}}}])
document

ADVERTISEMENT

00 votes

Related Articles

Related forms

Related Categories

Parent category: Education
Go
Page of 4