Saturday 21 February 2015

mongoDB : Double Grouping


You can send one group output as input to next group in mongoDB.

> db.fun.find()
{ "_id" : 0, "a" : 0, "b" : 0, "c" : 21 }
{ "_id" : 1, "a" : 0, "b" : 0, "c" : 54 }
{ "_id" : 2, "a" : 0, "b" : 1, "c" : 52 }
{ "_id" : 3, "a" : 0, "b" : 1, "c" : 17 }
{ "_id" : 4, "a" : 1, "b" : 0, "c" : 22 }
{ "_id" : 5, "a" : 1, "b" : 0, "c" : 5 }
{ "_id" : 6, "a" : 1, "b" : 1, "c" : 87 }
{ "_id" : 7, "a" : 1, "b" : 1, "c" : 97 }
>
>
> db.fun.aggregate([{$group:{_id:{a:"$a", b:"$b"}, c:{$max:"$c"}}}, {$group:{_id:"$_id.a", c:{$min:"$c"}}}])
{ "_id" : 0, "c" : 52 }
{ "_id" : 1, "c" : 22 }


Let’s observe above query, it contains two groups, group1 output is given as input to group2.

group1 “([{$group:{_id:{a:"$a", b:"$b"}, c:{$max:"$c"}}}” output looks like below.

{ "_id" : { "a" : 1, "b" : 1 }, "c" : 97 }
{ "_id" : { "a" : 1, "b" : 0 }, "c" : 22 }
{ "_id" : { "a" : 0, "b" : 1 }, "c" : 52 }
{ "_id" : { "a" : 0, "b" : 0 }, "c" : 54 }

group2 “{$group:{_id:"$_id.a", c:{$min:"$c"}}}” takes group1 input and return below data.

{ "_id" : 0, "c" : 52 }
{ "_id" : 1, "c" : 22 }



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment