mongodb3.2链接设置
try { ServerAddress serverAddress = new ServerAddress("localhost", 27017); List<ServerAddress> addrs = new ArrayList<ServerAddress>(); addrs.add(serverAddress); MongoCredential credential = MongoCredential.createScramSha1Credential("admin", "admin","admin".toCharArray()); List<MongoCredential> credentials = new ArrayList<MongoCredential>(); credentials.add(credential); //通过连接认证获取MongoDB连接 MongoClient mongoClient = new MongoClient(addrs,credentials); //连接到数据库 db = mongoClient.getDatabase("test"); MongoCollection<Document> collection = db.getCollection("aa"); } catch (Exception e) { System.err.println( e.getClass().getName() + ": " + e.getMessage() ); }
//条件查询并去重 public static List<String> query2(MongoCollection<Document> collection,long beginDay,long endDay) { //db.routedata.distinct(('lanmac'),{"time":{$gte:1464624000000,$lte:1464659580000}}) List<String> list = new ArrayList<String>(); Document query = new Document(); query.put("time", new BasicDBObject("$gte",beginDay).append("$lte",endDay)); MongoCursor<String> li = collection.distinct("lanmac",query,String.class ).iterator(); while (li.hasNext()) { String n = li.next(); list.add(n); } return list; }