標籤:pre on() rank compile double ase iter pat 支援
Mongodb是一個nosql型的資料庫,儲存的是類似於json對象,能夠支援類似於關係型資料庫的一些操作。以下是java操作mongodb。
一、建立串連(沒有使用任何架構,串連是自己寫的,同時在這個類寫了關閉串連的方法),傳入ip地址、連接埠和資料庫名稱(mongodb稱集合)
public class MongoDbConn { private static MongoClient mongoClient = null; private static MongoDatabase mongoDatabase = null; public static MongoDatabase getDatabase(String ipaddress,int port,String dbName) { mongoClient = new MongoClient(ipaddress, port); mongoDatabase = mongoClient.getDatabase(dbName); return mongoDatabase; } public static void closeDatabase(){ try{ if(mongoClient!=null){ mongoClient.close(); } }catch(Exception e){ throw new RuntimeException(); }finally{ mongoClient = null; } }}
二、使用操作,以下是查詢的例子
public List<Data> getAllAbsData(RankParam rankParam) { List<Data> dataList = new ArrayList<Data>(); MongoDatabase mongoDatabase = MongoDbConn.getDatabase("localhost", 27017, "area_new"); MongoCollection<Document> collection = mongoDatabase.getCollection("vaabs_monthly"); FindIterable<Document> findIterable = null; if ("vaabs".equals(rankParam.getIndexCode())) { if (rankParam.getAreaCode() == null || "".equals(rankParam.getAreaCode())) {// 全國 //db.vaabs_monthly.find({"$and":[{"indusId":300},{"areaCode":/.*0000$/}]}) Pattern queryPattern = Pattern.compile(".*0000$", Pattern.CASE_INSENSITIVE); BasicDBObject queryObject = new BasicDBObject(); queryObject.put("areaCode", queryPattern); queryObject.put("indusId", rankParam.getIndusId()); findIterable = collection.find(queryObject); }else {//全省所有市的資料 //db.vaabs_monthly.find({"$and":[{"indusId":300},{"date":"2007-01-31"},{"areaCode":/^13/},{"areaCode":/.*00$/},{"areaCode":{"$not":/.*0000$/}}]}) //Pattern startPattern = Pattern.compile("^13", Pattern.CASE_INSENSITIVE); Pattern startPattern = Pattern.compile("^"+rankParam.getAreaCode(), Pattern.CASE_INSENSITIVE); Pattern endPattern = Pattern.compile(".*00$", Pattern.CASE_INSENSITIVE); Pattern notPattern = Pattern.compile(".*0000$", Pattern.CASE_INSENSITIVE); BasicDBObject queryObject = new BasicDBObject().append(QueryOperators.AND, new BasicDBObject[]{new BasicDBObject("indusId",rankParam.getIndusId()), new BasicDBObject("areaCode",startPattern),new BasicDBObject("areaCode",endPattern),new BasicDBObject("areaCode", new BasicDBObject("$not",notPattern)) }); findIterable = collection.find(queryObject); } MongoCursor<Document> mongoCursor = findIterable.iterator(); while (mongoCursor.hasNext()) { Document document = mongoCursor.next(); dataList.add(new Data(document.getString("name"), document.getDouble("value"), document.getString("date"), document.getString("areaCode"), document.getInteger("indusId"))); } }else{ } return dataList; }
java中操作Mongodb