Skip to content
Ahmed Toumi edited this page Nov 13, 2016 · 27 revisions

Mongo DB

All those examples are inspired from mongo db univversity courses

Aggregation

Simple Examples

We will use the products collection as an example To start we would like to translate this SQL request to mongo db :

select manufacturer, count(*) from products group by manufacturer

the result will be : db.products.aggregate([
{$group:
{
_id:"$manufacturer",
num_products:{$sum:1}
}
}
])

A second example :

select category, count(*) from products group by category

the result will be :

db.products.aggregate([
{$group:
{
_id:"$category",
num_products:{$sum:1}
}
}
])

To Execute an aggregation query, mongo-db run through the collections that exist prior to stage of pipeline ($group) and then building a new set of documents with the _id as specified (manufacturer or category in the previous example) and then run the aggregation operator on the other fieldthat we have created (num_products in this example).

Aggregation Pipeline

the following are the stages in the aggregation pipeline

  1. $project -> reshape -> 1:1
  2. $match -> filter -> n:1
  3. $group -> aggregate -> n:1
  4. $sort -> sort -> 1:1
  5. $skip -> skips -> n:1
  6. $limit -> limits -> n:1
  7. $unwind -> normalize -> 1:n
  8. $out -> output -> 1:1
  9. $redact : security operator
  10. $geonear : to perform location queries

Next

Clone this wiki locally