您好,登錄后才能下訂單哦!
由于最近項目要使用mongodb來處理一些日志,提前學習了一下mongodb的一些基本用法,大概寫了一些常用的。
開發環境為:WIN7-64,JDK7-64,MAVEN3.3.9-64,IDEA2017-64.
程序基本結構為:
下面貼出核心代碼示例:
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>TestWebProjectMaven</groupId> <artifactId>TestWebProjectMaven</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>TestWebProjectMaven Maven Webapp</name> <!-- 設定主倉庫 --> <repositories> <!-- nexus私服 --> <repository> <id>nexus-repos</id> <name>Team Nexus Repository</name> <url>http://192.168.200.205:8081/nexus/content/groups/public/</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>true</enabled> </snapshots> </repository> </repositories> <!-- 設定插件倉庫 --> <pluginRepositories> <pluginRepository> <id>nexus-repos</id> <name>Team Nexus Repository</name> <url>http://192.168.200.205:8081/nexus/content/groups/public/</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>true</enabled> </snapshots> </pluginRepository> </pluginRepositories> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.1.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.1.6.RELEASE</version> </dependency> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>3.2.1</version> </dependency> <dependency> <groupId>org.jetbrains</groupId> <artifactId>annotations-java5</artifactId> <version>RELEASE</version> </dependency> <dependency> <groupId>commons-configuration</groupId> <artifactId>commons-configuration</artifactId> <version>1.10</version> </dependency> </dependencies> <build> <finalName>TestWebProjectMaven</finalName> <!-- 設置properties文件編譯到target目錄中,不然讀取不到配置文件 --> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> </includes> </resource> <resource> <directory>src/main/resources</directory> </resource> </resources> </build> </project>
mongodb.properties
MONGODB_IP=192.168.200.234 MONGODB_PORT=10143 MONGODB_DATABASE_NAME=runoob MONGODB_COLLECTION_NAME=test
MongodbUtil
package org.mbox.util; import com.mongodb.MongoClient; import com.mongodb.client.*; import com.mongodb.client.model.Filters; import com.mongodb.client.model.UpdateOptions; import com.mongodb.client.result.DeleteResult; import org.apache.commons.configuration.CompositeConfiguration; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.PropertiesConfiguration; import org.bson.Document; import org.bson.conversions.Bson; import org.bson.types.ObjectId; import org.mbox.model.PageVO; import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.*; /** * Created by pc on 2017/6/5. */ public class MongodbUtil { private static MongoClient MONGODB_CLIENT = null; private static String MONGODB_IP = null; private static Integer MONGODB_PORT = null; private static String MONGODB_DATABASE_NAME = null; private static String MONGODB_COLLECTION_NAME = null; static{ CompositeConfiguration compositeConfiguration = new CompositeConfiguration(); try { compositeConfiguration.addConfiguration(new PropertiesConfiguration("mongodb.properties")); } catch (ConfigurationException e) { e.printStackTrace(); } MONGODB_IP = compositeConfiguration.getString("MONGODB_IP"); MONGODB_PORT = compositeConfiguration.getInt("MONGODB_PORT"); MONGODB_DATABASE_NAME = compositeConfiguration.getString("MONGODB_DATABASE_NAME"); MONGODB_COLLECTION_NAME = compositeConfiguration.getString("MONGODB_COLLECTION_NAME"); MONGODB_CLIENT = new MongoClient(MONGODB_IP,MONGODB_PORT); } private MongodbUtil() { } /** * 初始化mongodb數據源 * @return */ public static MongoDatabase getMongodbDatabase(){ return MONGODB_CLIENT.getDatabase(MONGODB_DATABASE_NAME); } /** * 關閉MongoClient連接 */ public static void closeMongodbClient(){ if(null != MONGODB_CLIENT){ MONGODB_CLIENT.close(); MONGODB_CLIENT = null; } } /** * 獲取mongodb的表對象 * @return */ public static MongoCollection<Document> getMongoCollection(){ return getMongodbDatabase().getCollection(MONGODB_COLLECTION_NAME); } /** * 通過map插入一條數據到表中 * @param map */ public static void insertOneCollectionByMap(Map<String,Object> map){ getMongoCollection().insertOne(handleMap(map)); } /** * 通過集合map一次性插入多條數據到表中 * @param listMap */ public static void insertManyCollectionByMap(List<Map<String,Object>> listMap){ List<Document> list = new ArrayList<Document>(); for(Map<String,Object> map : listMap){ Document document = handleMap(map); list.add(document); } getMongoCollection().insertMany(list); } /** * 通過實體對象插入一條數據到表中 * @param obj */ public static void insertOneCollectionByModel(Object obj){ getMongoCollection().insertOne(handleModel(obj)); } /** * 通過集合實體對象一次性插入多條數據到表中 * @param listObj */ public static void insertManyCollectionByModel(List<Object> listObj){ List<Document> list = new ArrayList<Document>(); for(Object obj : listObj){ Document document = handleModel(obj); list.add(document); } getMongoCollection().insertMany(list); } /** * 通過手工拼接條件獲取查詢結果集 * 下面是拼接queryDocument例子 * document = new Document(); * 要注意value中的數據類型 * document.append("num",new Document("$eq",20));//相等 * document.append("num",new Document("$age",20));//不相等 * document.append("num",new Document("$gt",20));//大于 * document.append("num",new Document("$gte",21));//大于等于 * document.append("num",new Document("$lte",21));//小于等于 * document.append("num",new Document("$lt",21));//小于 * 下面是或的寫法 * List<Document> documentList = new ArrayList<Document>(); * documentList.add(new Document("num",1)); * documentList.add(new Document("num",2)); * document.append("$or",documentList); * @param queryDocument * @param sortDocument * @param pageVO * @return */ public static String queryCollectionByCondition(Document queryDocument,Document sortDocument,PageVO pageVO){ if(null == queryDocument || null == sortDocument || null == pageVO){ return null; }else{ String returnList = getQueryCollectionResult(queryDocument,sortDocument,pageVO); return returnList; } } /** * 通過不定條件map查詢出表中的所有數據,只限于等于的條件 * @param map * @param sortDocument * @param pageVO * @return */ public static String queryCollectionByMap(Map<String,Object> map,Document sortDocument,PageVO pageVO){ String sql = getQueryCollectionResult(handleMap(map),sortDocument,pageVO); return sql; } /** * 通過不定條件實體對象obj查詢出表中的所有數據,只限于等于的條件 * @param obj * @param sortDocument * @param pageVO * @return */ public static String queryCollectionByModel(Object obj,Document sortDocument,PageVO pageVO){ String sql = getQueryCollectionResult(handleModel(obj),sortDocument,pageVO); return sql; } /** * 接收Document組裝的查詢對象,處理子集查詢結果并以JSON的形式返回前端 * @param queryDocument * @param sortDocument * @param pageVO * @return */ private static String getQueryCollectionResult(Document queryDocument,Document sortDocument,PageVO pageVO){ FindIterable<Document> findIterable = getMongoCollection().find(queryDocument) .sort(sortDocument).skip((pageVO.getPageNum()-1)*pageVO.getPageSize()).limit(pageVO.getPageSize()); MongoCursor<Document> mongoCursor = findIterable.iterator(); StringBuilder sql = new StringBuilder(); Integer lineNum = 0; while(mongoCursor.hasNext()){ sql.append("{"); Document documentVal = mongoCursor.next(); Set<Map.Entry<String,Object>> sets = documentVal.entrySet(); Iterator<Map.Entry<String,Object>> iterators = sets.iterator(); while(iterators.hasNext()){ Map.Entry<String,Object> map = iterators.next(); String key = map.getKey(); Object value = map.getValue(); sql.append("\""); sql.append(key); sql.append("\""); sql.append(":"); sql.append("\""); sql.append((value == null ? "" : value)); sql.append("\","); } sql.deleteCharAt(sql.lastIndexOf(",")); sql.append("},"); lineNum++; } //這里判斷是防止上述沒值的情況 if(sql.length() > 0){ sql.deleteCharAt(sql.lastIndexOf(",")); } String returnList = getFinalQueryResultsSql(lineNum,sql.toString()); return returnList; } /** * 拼接返回前端的JSON串 * @param lineNum 子集中JSON的條數 * @param querySql 子集中的所有結果JSON * @return */ private static String getFinalQueryResultsSql(Integer lineNum,String querySql) { StringBuilder sql = new StringBuilder(); sql.append("{"); sql.append("\""); sql.append("jsonRoot"); sql.append("\""); sql.append(":"); sql.append("\""); sql.append(lineNum); sql.append("\","); sql.append("\""); sql.append("jsonList"); sql.append("\""); sql.append(":"); sql.append("["); sql.append(querySql); sql.append("]"); sql.append("}"); return sql.toString(); } /** * 以list的形式獲取mongdb庫中的所有表 * @return */ public static List<String> getALLCollectionNameOfList(){ List<String> list = new ArrayList<String>(); MongoIterable<String> mongoIterable = getMongodbDatabase().listCollectionNames(); for(String name : mongoIterable){ list.add(name); } return list; } /** * 以map的形式獲取mongdb庫中的所有表 * @return */ public static Map<String,String> getALLCollectionNameOfMap() { Map<String,String> map = new HashMap<String,String>(); MongoIterable<String> mongoIterable = getMongodbDatabase().listCollectionNames(); for(String name : mongoIterable){ map.put(name,name); } return map; } /** * 獲取表中的數據條數 * @param queryDocument 傳null為查詢表中所有數據 * @return */ public static Integer queryCollectionCount(Document queryDocument){ int count = (int) getMongoCollection().count(queryDocument); return count; } /** * 通過表ID獲取某條數據 * @param id * @return */ public static String queryCollectionModelById(String id){ ObjectId objectId = new ObjectId(id);//注意在處理主鍵問題上一定要用ObjectId轉一下 Document document = getMongoCollection().find(Filters.eq("_id",objectId)).first(); return (document == null ? null : document.toJson()); } /** * 根據ID更新某一條數據 * @param id 查詢條件主鍵ID * @param updateMap 更新內容,如果是此ID中不存在的字段,那么會在此ID對應的數據中加入新的字段內容 * 注意這里跟updateOptions.upsert(ifInsert);沒關系 */ public static void updateCollectionById(String id,Map<String,Object> updateMap){ Document queryDocument = new Document(); ObjectId objId = new ObjectId(id);//注意在處理主鍵問題上一定要用ObjectId轉一下 queryDocument.append("_id", objId); Document updateDocument = handleMap(updateMap); getMongoCollection().updateOne(queryDocument,new Document("$set",updateDocument)); } /** * 根據某幾個字段更新多條數據,document的條件拼接可參考queryCollectionByCondition方法 * @param queryDocument 查詢條件,一定不要加_id,根據ID處理的話參考updateCollectionById方法 * @param updateDocument 更新內容,當查詢條件和更新內容有出入并且ifInsert為true時才插入 * @param ifInsert 數據不存在是否插入,true插入,false不插入 */ public static void updateCollectionByCondition(Document queryDocument,Document updateDocument,Boolean ifInsert){ UpdateOptions updateOptions = new UpdateOptions(); updateOptions.upsert(ifInsert); getMongoCollection().updateMany(queryDocument,new Document("$set",updateDocument),updateOptions); } /** * 根據ID刪除某一條數據 * @param id * @return */ public static Integer deleteCollectionById(String id){ ObjectId objectId = new ObjectId(id); Bson bson = Filters.eq("_id",objectId); DeleteResult deleteResult = getMongoCollection().deleteOne(bson); int count = (int) deleteResult.getDeletedCount(); return count; } /** * 根據MAP刪除表中的某些數據 * @param map */ public static void deleteCollectionByMap(Map<String,Object> map){ getMongoCollection().deleteMany(handleMap(map)); } /** * 根據實體對象刪除表中的某些數據 * @param obj */ public static void deleteCollectionByModel(Object obj){ getMongoCollection().deleteMany(handleModel(obj)); } /** * 根據預先手工拼接的document刪除表中的某些數據 * @param document */ public static void deleteCollectionByDocument(Document document){ getMongoCollection().deleteMany(document); } /** * 通過實體對象obj拼接document * @param obj * @return */ private static Document handleModel(Object obj){ Document document = null; if(obj != null){ document = new Document(); try { Class clz = obj.getClass(); Field fields[] = clz.getDeclaredFields(); for(Field field : fields){ String fieldName = field.getName(); PropertyDescriptor propertyDescriptor = new PropertyDescriptor(fieldName,clz); Method method = propertyDescriptor.getReadMethod(); Object fieldValue = method.invoke(obj); document.append(fieldName,(fieldValue == null ? "" : fieldValue)); } } catch (IntrospectionException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } }else{ document = new Document("",""); } return document; } /** * 通過集合map拼接document * @param map * @return */ private static Document handleMap(Map<String,Object> map){ Document document = null; if(null != map){ document = new Document(); Set<String> sets = map.keySet(); Iterator<String> iterators = sets.iterator(); while(iterators.hasNext()){ String key = iterators.next(); Object value = map.get(key); document.append(key,(value == null ? "" : value)); } }else{ document = new Document("","");//這種設置查詢不到任何數據 } return document; } /** * 刪除某個庫 * @param databaseName */ public static void dropDatabase(String databaseName){ MONGODB_CLIENT.dropDatabase(databaseName); } /** * 刪除某個庫中的某個表 * @param databaseName * @param collectionName */ public static void dropCollection(String databaseName,String collectionName){ MONGODB_CLIENT.getDatabase(databaseName).getCollection(collectionName).drop(); } /** * 下述方式個人并不推薦,沒有直接用document直接拼串方便 */ public static void testquery(){ List<Integer> list = new ArrayList<Integer>(); list.add(20); list.add(21); list.add(22); FindIterable<Document> findIterable = //getMongoCollection().find(Filters.and(Filters.lt("num",22),Filters.gt("num",17))); //getMongoCollection().find(Filters.in("num",17,18)); getMongoCollection().find(Filters.nin("num",list)); MongoCursor<Document> mongoCursor = findIterable.iterator(); while(mongoCursor.hasNext()){ Document document = mongoCursor.next(); System.out.println(document.toJson()); } } }
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。