mongodb命令行group分组和java代码中group分组

group分组统计是数据库比较常用的功能,mongodb也不例外。不过相对于普通的增删改查,group操作就略微麻烦一些,
这里对group在shell中的操作、使用java原生代码操作以及集成spring进行操作进行一个简单的归纳总结,分组的途径和方法应该都有多种,这里每一样只举一例。

本例中数据源如下:
mongodb命令行group分组和java代码中group分组
mongodb命令行group分组和java代码中group分组

需要使用group实现的目的是:按年龄分组统计出每一组的数量。

1、mongo shell中执行如下命令:

db.test.group({
    key:{"age":1},
    initial:{"count":0},
   $reduce:function(doc,out){ out.count++; } ,
   $finalize:function(out){ return out; }
 }
 )

执行代码及结果如图:
mongodb命令行group分组和java代码中group分组

mongodb命令行group分组和java代码中group分组

2、java原生代码进行上述操作:

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(out){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);
            }
        }
    }
}

执行结果如图:
mongodb命令行group分组和java代码中group分组

3、集成spring后的操作:


dao方法实现代码:
  /**
     * mongodb简单分组查询
     *
     * @author:tuzongxun
     * @Title: mongoGroup
     * @param @return
     * @date Jul 19, 2016 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;
    }

对应的实体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 age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "UserModel [name=" + name + ", age=" + age + "]";
    }

}

junit测试方法:
@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);
            }
        }
    }

运行结果如图:
mongodb命令行group分组和java代码中group分组
mongodb命令行group分组和java代码中group分组




上一篇:Redis:安装


下一篇:1171 Big Event in HDU 01背包