标签:
db.test.group({ key:{"age":1}, initial:{"count":0}, $reduce:function(doc,out){ out.count++; } , $finalize:function(out){ return out; } } )
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简单分组查询 * * @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; }
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 + "]"; } }
@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分组
标签:
原文地址:http://blog.csdn.net/tuzongxun/article/details/51952416