Mongodb group and sort -


i using mongod database rails 3

how execute similar code following sql in mongod. there way execute group , sort in mongod

select a,b,sum(c) csum coll active=1 group a,b order 

thanks

inspired example on mongo's website.

generate dummy data:

> db.stack.insert({a:1,b:1,c:1,active:1}) > db.stack.insert({a:1,b:1,c:2,active:0}) > db.stack.insert({a:1,b:2,c:3,active:1}) > db.stack.insert({a:1,b:2,c:2,active:0}) > db.stack.insert({a:2,b:1,c:3,active:1}) > db.stack.insert({a:2,b:1,c:10,active:1}) > db.stack.insert({a:2,b:2,c:10,active:0}) > db.stack.insert({a:2,b:2,c:5,active:1}) 

mongo query:

> db.stack.aggregate( ... {$match:{active:1}}, ... {$group:{_id:{a:"$a", b:"$b"}, csum:{$sum:"$c"}}}, ... {$sort:{"_id.a":1}}) 

result:

{"result" : [     {"_id" : {"a" : 1,"b" : 2},"csum" : 3},     {"_id" : {"a" : 1,"b" : 1},"csum" : 1},     {"_id" : {"a" : 2,"b" : 2},"csum" : 5},     {"_id" : {"a" : 2,"b" : 1},"csum" : 13} ],"ok" : 1} 

(note: reformatted shell result bit more readable)


Comments

Popular posts from this blog

c# - SharpSVN - How to get the previous revision? -

c++ - Is it possible to compile a VST on linux? -

url - Querystring manipulation of email Address in PHP -