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

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

本例中数据源如下:


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

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

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

执行代码及结果如图:


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);
            }
        }
    }
}

执行结果如图:


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);
            }
        }
    }

运行结果如图:





涂宗勋 CSDN认证博客专家 web安全 系统安全 安全架构
【若想不迷路,记得点关注,动动小手指,点点全是福】

6年java工作经验,现居湖北武汉,有过支付、OA、CA、OAUTH2等工作经验,现从事车联网行业。
爱好分享,个人博客blog.tzxcode.cn,微信tuzongxun,qq1160569243,欢迎来撩。
©️2020 CSDN 皮肤主题: 成长之路 设计师: Amelia_0503 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值