MongoDB Command Line group grouping and group grouping in Java code

Source: Internet
Author: User
Tags mongo shell

Group grouping statistics is a common function of database, MongoDB is no exception. However, relative to the normal additions and deletions, the group operation is a little more trouble, here to the group in the shell operation, the use of Java native Code operation and integration of spring operation to a simple summary, the grouping of ways and methods should have a variety of, here each one only to cite one example.
The data source in this example is as follows:

The purpose of the group implementation is to count the number of each group by age group.
1. Execute the following command in the MONGO Shell:
Db.test.group ({    key:{"age": 1},    initial:{"Count": 0},   $reduce: function (doc,out) {out.count++;},   $ Finalize:function (out) {return out;}} )

Execute code and Results

2, Java native code to do the above:
public class Montest {public static void main (string[] args) {mongroup ();        public static void Mongroup () {serveraddress sa = new ServerAddress ("192.168.0.201", 37017);        list<mongocredential> mongocredentiallist = new arraylist<mongocredential> ();        Mongocredentiallist.add (mongocredential.createmongocrcredential ("admin", "admin", "123456". ToCharArray ()));        Mongo client = new Mongoclient (SA, mongocredentiallist);        DB database = Client.getdb ("admin");        Dbcollection coll = database.getcollection ("test");        DBObject keys = new Basicdbobject ("Age", 1);        DBObject condition = null;        DBObject initial = new Basicdbobject ("Count", 0);        String reduce = "function (doc,out) {out.count++;}";        String Finalize = "function" {return out;} ";        Basicdblist dblist = (basicdblist) coll.group (keys, condition, initial, reduce, finalize); if (dblist! = null) {for (int i = 0; i < dblist.siZe ();                i++) {DBObject obj = (dbobject) dblist.get (i);                Object age = Obj.get ("Age");                Object count = Obj.get ("Count");            System.out.println ("Age:" + Age + ", Count:" + count); }        }    }}

Execution results

3. Operation after integration with spring:
Environment construction can be consulted: http://blog.csdn.net/tuzongxun/article/details/51404529
Dao Method implementation code:
  /**     * MongoDB Simple packet Query     *      * @author: Tuzongxun     * @Title: Mongogroup     * @param @return     * @date Jul 19, 8:36:19 AM     * @throws *    /@Override public    basicdblist Mongogroup () {        //TODO auto-generated Method Stub        GroupBy GroupBy = Groupby.key ("Age"). Initialdocument ("{count:0}"). Reducefunction ("function (Doc, Out) {out.count++} ')            . Finalizefunction ("function (out) {return out;}");        groupbyresults<usermodel> res = mongotemplate.group ("Test", GroupBy, Usermodel.class);        DBObject obj = Res.getrawresults ();        Basicdblist dblist = (basicdblist) obj.get ("RetVal");        return dblist;    }


The corresponding entity model:
Package Spring_mongo.models;import Java.io.serializable;public class Usermodel implements Serializable {    private Static final Long serialversionuid = 1L;    private String name;    private int age;    Public Usermodel (String name, Int. age) {        super ();        this.name = name;        This.age = age;    }    Public String GetName () {        return name;    }    public void SetName (String name) {        this.name = name;    }    public int getage () {        return age;    }    public void Setage (int.) {        this.age = age;    }    @Override public    String toString () {        return ' Usermodel [name= "+ name +", age= "+ Age +"] ";    }}

JUnit test methods:
@Test public    void Mongogroup () {        basicdblist dblist = Userdao.mongogroup ();        if (dblist! = null) {for            (int i = 0; i < dblist.size (); i++) {                DBObject obj = (dbobject) dblist.get (i);                Object age = Obj.get ("Age");                Object count = Obj.get ("Count");                System.out.println ("Age:" + Age + ", Count:" + count);}}}    

Run results




MongoDB Command Line group grouping and group grouping in Java code

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.