Tuesday, June 17, 2014

MongoDb - using $sum in aggregation

Data
{ "_id" : 1, "city" : "delhi", "state" : "delhi", "pop" : 10}
{ "_id" : 2, "city" : "chandigarh", "state" : "punjab", "pop" : 10}
{ "_id" : 3, "city" : "delhi", "state" : "delhi", "pop" : 10}
{ "_id" : 4, "city" : "delhi", "state" : "delhi", "pop" : 10}
{ "_id" : 5, "city" : "shimla", "state" : "hp", "pop" : 10}
{ "_id" : 6, "city" : "shimla", "state" : "hp", "pop" : 10}

db.test.aggregate([
{ $group : { _id : "$state", population : { $sum : "$pop"}, count : { $sum : 1}}},
{ $sort : {population : 1}}
])

Result
{ "_id" : "punjab", "population" : 10, "count" : 1 }
{ "_id" : "hp", "population" : 20, "count" : 2 }
{ "_id" : "delhi", "population" : 30, "count" : 3 }

db.test.aggregate([
{ $group : { _id : { state : "$state", city : "$city" }, population : { $sum : "$pop"}, count : { $sum : 1}}},
{ $sort : {population : 1}}
])

{ "_id" : { "state" : "punjab", "city" : "chandigarh" }, "population" : 10, "count" : 1 }
{ "_id" : { "state" : "hp", "city" : "shimla" }, "population" : 20, "count" : 2}
{ "_id" : { "state" : "delhi", "city" : "delhi" }, "population" : 30, "count" :3 }

No comments:

Post a Comment