MongoDB – Aggregation Expressions

sum
avg
min
max
push
addtoset
first
last
=================

Which of the following aggregation expressions must be used in conjunction with a sort to make any sense?
$first, $last
===================
use agg
db.products.aggregate([
{$group:
{
_id: {
“manufacturer”:”$manufacturer”
},
num_products:{$sum:”$price”}
}
}
])
================

mongoimport is independent command. Don’t run this from shell.
>mongoimport –db agg –collection zips –file zips.json

>mongo
>use agg
>db.zips.count()

use agg;
db.zips.aggregate([{“$group”:{“_id”:”$state”, “population”:{$sum:”$pop”}}}])

use agg;
db.zips.aggregate([{“$group”:{“_id”:”$state”, “average_pop”:{$avg:”$pop”}}}])

================
addToSet

use agg
db.products.aggregate([
{$group:
{
_id: {
“maker”:”$manufacturer”
},
categories:{$addToSet:”$category”}
}
}
])

{ “_id” : { “maker” : “Amazon” }, “categories” : [ “Tablets” ] }
{ “_id” : { “maker” : “Google” }, “categories” : [ “Tablets” ] }
{ “_id” : { “maker” : “Sony” }, “categories” : [ “Laptops” ] }
{ “_id” : { “maker” : “Samsung” }, “categories” : [ “Tablets”, “Cell Phones” ] }
{ “_id” : { “maker” : “Apple” }, “categories” : [ “Tablets”, “Laptops” ] }

================

Write an aggregation query that will return the postal codes that cover each city.

use agg;

db.zips.aggregate([{$group:{
“_id”: “$city”,
“postal_codes”: {“$addToSet”:”$_id”}
}}])
================
use agg
db.products.aggregate([
{$group:
{
_id: {
“maker”:”$manufacturer”
},
maxprice:{$max:”$price”}
}
}
])
================

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s