转自:
http://blog.csdn.net/maosijunzi/article/details/42105927
数据库数据如下:
上代码:
[java] view plaincopyprint?- public static void main(String[] args) {
- UserDao userDao = new UserDao();
- userDao.juhe();
- }
- public void juhe() {
- DB myMongo = MongoManager.getDB("myMongo");
- DBCollection userCollection = myMongo.getCollection("user");
- // 使用 count 统计数量
- System.out.println(userCollection.count());
- // 使用distinct 统计所有的address
- List distinct = userCollection.distinct("address");
- System.out.println(distinct);
- //使用group 查询每年(year)中age最大的人
- BasicDBObject key = new BasicDBObject("year",true);
- BasicDBObject cond = new BasicDBObject("id",new BasicDBObject(QueryOperators.GT,0));
- BasicDBObject initial = new BasicDBObject("age",0);
- String reduce = "function (doc,prev){"
- +"if(doc.age>prev.age){"
- +"prev.age=doc.age;"
- +"prev.name=doc.name"
- +"}"
- +"}";
- BasicDBList group = (BasicDBList) userCollection.group(key,cond,initial,reduce);
- System.out.println(group);
- }
输出结果如下:
[plain] view plaincopyprint?- 11
- [ "1" , "2" , "5" , "6" , "7" , "8" , "9" , "11" , "12"]
- [ { "year" : 2014.0 , "age" : 17.0 , "name" : "2"} , { "year" : 2013.0 , "age" : 17.0 , "name" : "2"}]