1. 程式人生 > >java操作mongodb(聚合函式)

java操作mongodb(聚合函式)

資料庫資料如下:

上程式碼:

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

	}

輸出結果如下:

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"}]