MongoDB – Aggregation

db.stuff.insert({ “_id” : ObjectId(“50b26f9d80a78af03b5163c8”), “a” : 1, “b” : 1, “c” : 1 })
db.stuff.insert({ “_id” : ObjectId(“50b26fb480a78af03b5163c9”), “a” : 2, “b” : 2, “c” : 1 })
db.stuff.insert({ “_id” : ObjectId(“50b26fbf80a78af03b5163ca”), “a” : 3, “b” : 3, “c” : 1 })
db.stuff.insert({ “_id” : ObjectId(“50b26fcd80a78af03b5163cb”), “a” : 3, “b” : 3, “c” : 2 })
db.stuff.insert({ “_id” : ObjectId(“50b26fd380a78af03b5163cc”), “a” : 3, “b” : 5, “c” : 3 })

 

db.stuff.aggregate([{$group:{_id:'$c'}}])

{ "_id" : 3 }
{ "_id" : 2 }
{ "_id" : 1 }


---------------------

Compount Grouping

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

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

---------------------
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