See: www.linuxidc.comLinux2013-0482787.htm Group for convenience I still paste my table structure: the same as the database g
See: http://www.linuxidc.com/Linux/2013-04/82787.htm Group for convenience I still paste my table structure: the same as the database g
Next to the previous article... see:
Group
For convenience, I still paste the structure of my table:
Similar to databases, group is often used for statistics. There are many restrictions on MongoDB group. For example, if the returned result set cannot exceed 16 MB, the group operation will not process more than 10000 unique keys. It seems that indexes cannot be used [not very sure].
Group requires several parameters.
I will test them in Java.
Users in the age statistics set. Spring Schema is the same as the previous one. With the intent template object, we can do everything. Use age to count user test code, for example:
@ Test
Public void testGroupBy () throws Exception {
String reduce = "function (doc, aggr) {" +
"Aggr. count + = 1;" +
"}";
Query query = Query. query (Criteria. where ("age"). exists (true ));
DBObject result = jsontemplate. getCollection ("person"). group (new BasicDBObject ("age", 1 ),
Query. getQueryObject (),
New BasicDBObject ("count", 0 ),
Reduce );
Map map = result. toMap ();
System. out. println (map );
For (Map. Entry o: map. entrySet ()){
System. out. println (o. getKey () + "" + o. getValue ());
}
}
Key is new BasicDBObject ("age", 1)
Cond: Criteria. where ("age"). exists (true ). That is, the user has the age field.
Initial: new BasicDBObject ("count", 0), that is, the number of people in the initialization reduce is 0. Suppose we want to add 10 fake users to every age during the query. We only need to input BasicDBObject ("count", 10 ).
Reduce is a javascript function of reduce.
The preceding execution output is as follows:
2 [age: 23.0, count: 1.0]
1 [age: 25.0, count: 1.0]
0 [age: 24.0, count: 1.0]
The preceding sequence number is added to Mongo's java-driver. We can see that the result is later.