import java.net.UnknownHostException; import com.mongodb.BasicDBList; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.Mongo; public class MongoDBTest { private static DB db = null; static{ Mongo mongo = null; try { mongo = new Mongo("localhost", 27017); } catch (UnknownHostException e) { e.printStackTrace(); } db = mongo.getDB("TestDB"); //连接数据 } /** * select count(*) from list */ public Long m1() { DBCollection collection = db.getCollection("list"); return collection.count(); } /** * select count(*) from list where userId = 'orange' */ public Long m2(){ DBCollection listCollection = db.getCollection("list"); BasicDBObject query =new BasicDBObject(); query.put("userId", "orange"); return listCollection.count(query); } /** * select count(*) from list where userId = 'orange' and time >= '20101201' and time <= '20101211' */ public Long m3(){ DBCollection listCollection = db.getCollection("list"); BasicDBObject query =new BasicDBObject(); query.put("userId","orange"); query.put("time", new BasicDBObject("$gte", "20101201").append("$lte", "20101211")); return listCollection.count(query); } /** * select count(distinct(userId)) from detail where time >= '20101201' and time <='20101211' */ public int m4() { DBCollection collection = db.getCollection("detail"); BasicDBObject query = new BasicDBObject(); query.put("time", new BasicDBObject("$gte", "20101201").append("$lte", "20101211")); return collection.distinct("userId", query).size(); } /** * select date_format(time, '%Y-%m-%d %H') as sj ,count(*) from detail group by sj */ public void m5() { DBCollection collection = db.getCollection("detail"); String formatDate = "function(obj,doc){" + "var date = new Date(doc.time);" + "var dateKey = date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate(); " + "return {'time':datekey}" + "}"; BasicDBObject key = new BasicDBObject(); key.put(formatDate, true); // 要分组的列 BasicDBObject query = new BasicDBObject(); // where条件 String reduce = "function (obj, prev) {prev.count++}"; BasicDBObject initial = new BasicDBObject(); initial.append("count", 0); // 每列初始值 BasicDBList group = (BasicDBList) collection.group(key, query, initial, reduce); System.out.println(group); } }