MongoDB – Aggregation

use agg
db.products.drop()

db.products.insert({‘name’:’iPad 16GB Wifi’, ‘manufacturer’:”Apple”,
‘category’:’Tablets’,
‘price’:499.00})
db.products.insert({‘name’:’iPad 32GB Wifi’, ‘category’:’Tablets’,
‘manufacturer’:”Apple”,
‘price’:599.00})
db.products.insert({‘name’:’iPad 64GB Wifi’, ‘category’:’Tablets’,
‘manufacturer’:”Apple”,
‘price’:699.00})
db.products.insert({‘name’:’Galaxy S3′, ‘category’:’Cell Phones’,
‘manufacturer’:’Samsung’,
‘price’:563.99})
db.products.insert({‘name’:’Galaxy Tab 10′, ‘category’:’Tablets’,
‘manufacturer’:’Samsung’,
‘price’:450.99})
db.products.insert({‘name’:’Vaio’, ‘category’:’Laptops’,
‘manufacturer’:”Sony”,
‘price’:499.00})
db.products.insert({‘name’:’Macbook Air 13inch’, ‘category’:’Laptops’,
‘manufacturer’:”Apple”,
‘price’:499.00})
db.products.insert({‘name’:’Nexus 7′, ‘category’:’Tablets’,
‘manufacturer’:”Google”,
‘price’:199.00})
db.products.insert({‘name’:’Kindle Paper White’, ‘category’:’Tablets’,
‘manufacturer’:”Amazon”,
‘price’:129.00})
db.products.insert({‘name’:’Kindle Fire’, ‘category’:’Tablets’,
‘manufacturer’:”Amazon”,
‘price’:199.00})
————————-
use agg
db.products.aggregate([
{$group:
{
_id:”$manufacturer”,
num_products:{$sum:1}
}
}
])

{ “_id” : “Amazon”, “num_products” : 2 }
{ “_id” : “Google”, “num_products” : 1 }
{ “_id” : “Sony”, “num_products” : 1 }
{ “_id” : “Samsung”, “num_products” : 2 }
{ “_id” : “Apple”, “num_products” : 4 }
————————-
use agg
db.products.aggregate([
{$group:
{
_id:”$category”,
num_products:{$sum:1}
}
}
])

{ “_id” : “Laptops”, “num_products” : 2 }
{ “_id” : “Cell Phones”, “num_products” : 1 }
{ “_id” : “Tablets”, “num_products” : 7 }
————————-

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