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 NB: to import data in mongodb use this command line
mongoimport --db dbName --collection collectionName fileName.json

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

Aggregation expressions

  1. $sum : When would like to calculate a population of a state if we know already the population on cities

mongoimport --db agg --collection zips zips.json db.states.aggregate([ {$group: {_id:"$state", population:{$sum:"$pop"} } }])

  1. $avg

$min, $max, $push, $addToSet, $first, $last.

Aggregation with compound grouping

Now we would like to translate a more complicated query that combine more than one keys for grouping.

SQL Query :
select manufacturer, category, count(*) from products group by manufacturer, category

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

We have to explain that mongo db accept an object (json) in the _id field and that what we use to execute an aggregation we multiple key.

Clone this wiki locally