mongo java group操作

		DBCollection table = getCollection();
		
		// 根据name分组,条件sex="1"
		BasicDBObject key = new BasicDBObject("name", true);  // 表中的字段
		BasicDBObject cond = <span style="font-family: Arial, Helvetica, sans-serif;">new BasicDBObject("sex", "1"); </span>

		BasicDBObject initial = new BasicDBObject();  
		initial.append("count", 0);  
		String reduce = "function Reduce(doc, out) { " +  
		        "    out.count +=1;"+    
		        "}";  
		String fn = "function Finalize(out) {return out;}";  
		final  BasicDBList  group = (BasicDBList) table.group(key, cond, initial, reduce, fn); 
		int count= 0;

		for(Object obj:group){
			JSONObject j = JSONObject.fromObject(obj);
	                String name = j.getString("name");
                        int count = j.getInt("count");
		}

你可能感兴趣的:(mongo)