Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select Max() with "group by" in mongodb

Tags:

Please help me to convert this select sentence to mongodb:

Select Name, Max(Value) From table1 Group By Name 

I read this document: http://www.mongodb.org/display/DOCS/Aggregation#Aggregation-Group

but still dont know how to apply Max() method instead SUM() as that document.

Thank you.

like image 590
spidermanit Avatar asked May 16 '12 05:05

spidermanit


People also ask

Can we use group by in MongoDB?

MongoDB group by is used to group data from the collection, we can achieve group by clause using aggregate function and group method in MongoDB. While using aggregate function with group by clause query operations is faster as normal query, basically aggregate function is used in multiple condition.

What is _ID in Group MongoDB?

The _id expression specifies the group key. If you specify an _id value of null, or any other constant value, the $group stage returns a single document that aggregates values across all of the input documents.

How do I get group count in MongoDB?

user. group({ "key": { "province": true }, "initial": { "count": 0 }, "reduce": function(obj, prev) { if (true != null) if (true instanceof Array) prev. count += true.


1 Answers

I have created Mongo Collection as follows.

{ "_id" : ObjectId("4fb36bfd3d1c88bfa15103b1"), "name" : "bob", "value" : 5 } { "_id" : ObjectId("4fb36c033d1c88bfa15103b2"), "name" : "bob", "value" : 3 } { "_id" : ObjectId("4fb36c063d1c88bfa15103b3"), "name" : "bob", "value" : 7 } { "_id" : ObjectId("4fb36c0c3d1c88bfa15103b4"), "name" : "john", "value" : 2 } { "_id" : ObjectId("4fb36c103d1c88bfa15103b5"), "name" : "john", "value" : 4 } { "_id" : ObjectId("4fb36c143d1c88bfa15103b6"), "name" : "john", "value" : 8 } { "_id" : ObjectId("4fb36c163d1c88bfa15103b7"), "name" : "john", "value" : 6 } 

Then by using the following code I group it by their name and max(value)

db.table1.group(     {key: {name:true},         reduce: function(obj,prev) {              if (prev.maxValue < obj.value) {                  prev.maxValue = obj.value;              }           },     initial: { maxValue: 0 }} ); 

The result is shown as

[     {         "name" : "bob",         "maxValue" : 7     },     {         "name" : "john",         "maxValue" : 8     } ] 

It is much simpler with the aggregation framework. You can get the same result with the following code by using aggregation framework.

db.table1.aggregate([     {        $group:{_id:"$name", "maxValue": {$max:"$value"}}     } ]); 
like image 76
Parvin Gasimzade Avatar answered Oct 21 '22 15:10

Parvin Gasimzade