我常常對MongoDB進行一些基礎操做,將這些經常使用操做合併到一個工具類中,方便本身開發使用。java
沒用Spring Data、Morphia等框架是爲了減小學習、維護成本,另外本身直接JDBC方式的話能夠更靈活,爲本身之後的積累留一個腳印。mongodb
JAVA驅動版本:數據庫
<!-- MongoDB驅動 --> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>3.0.2</version> </dependency>
工具類代碼以下:apache
package utils; import java.util.ArrayList; import java.util.List; 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 com.mongodb.BasicDBObject; import com.mongodb.MongoClient; import com.mongodb.MongoClientOptions; import com.mongodb.MongoClientOptions.Builder; import com.mongodb.WriteConcern; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCursor; import com.mongodb.client.MongoDatabase; import com.mongodb.client.MongoIterable; import com.mongodb.client.model.Filters; import com.mongodb.client.result.DeleteResult; /** * MongoDB工具類 Mongo實例表明了一個數據庫鏈接池,即便在多線程的環境中,一個Mongo實例對咱們來講已經足夠了<br> * 注意Mongo已經實現了鏈接池,而且是線程安全的。 <br> * 設計爲單例模式, 因 MongoDB的Java驅動是線程安全的,對於通常的應用,只要一個Mongo實例便可,<br> * Mongo有個內置的鏈接池(默認爲10個) 對於有大量寫和讀的環境中,爲了確保在一個Session中使用同一個DB時,<br> * DB和DBCollection是絕對線程安全的<br> * * @author zhoulingfei * @date 2015-5-29 上午11:49:49 * @version 0.0.0 * @Copyright (c)1997-2015 NavInfo Co.Ltd. All Rights Reserved. */ public enum MongoDBUtil { /** * 定義一個枚舉的元素,它表明此類的一個實例 */ instance; private MongoClient mongoClient; static { System.out.println("===============MongoDBUtil初始化========================"); CompositeConfiguration config = new CompositeConfiguration(); try { config.addConfiguration(new PropertiesConfiguration("mongodb.properties")); } catch (ConfigurationException e) { e.printStackTrace(); } // 從配置文件中獲取屬性值 String ip = config.getString("host"); int port = config.getInt("port"); instance.mongoClient = new MongoClient(ip, port); // or, to connect to a replica set, with auto-discovery of the primary, supply a seed list of members // List<ServerAddress> listHost = Arrays.asList(new ServerAddress("localhost", 27017),new ServerAddress("localhost", 27018)); // instance.mongoClient = new MongoClient(listHost); // 大部分用戶使用mongodb都在安全內網下,但若是將mongodb設爲安全驗證模式,就須要在客戶端提供用戶名和密碼: // boolean auth = db.authenticate(myUserName, myPassword); Builder options = new MongoClientOptions.Builder(); // options.autoConnectRetry(true);// 自動重連true // options.maxAutoConnectRetryTime(10); // the maximum auto connect retry time options.connectionsPerHost(300);// 鏈接池設置爲300個鏈接,默認爲100 options.connectTimeout(15000);// 鏈接超時,推薦>3000毫秒 options.maxWaitTime(5000); // options.socketTimeout(0);// 套接字超時時間,0無限制 options.threadsAllowedToBlockForConnectionMultiplier(5000);// 線程隊列數,若是鏈接線程排滿了隊列就會拋出「Out of semaphores to get db」錯誤。 options.writeConcern(WriteConcern.SAFE);// options.build(); } // ------------------------------------共用方法--------------------------------------------------- /** * 獲取DB實例 - 指定DB * * @param dbName * @return */ public MongoDatabase getDB(String dbName) { if (dbName != null && !"".equals(dbName)) { MongoDatabase database = mongoClient.getDatabase(dbName); return database; } return null; } /** * 獲取collection對象 - 指定Collection * * @param collName * @return */ public MongoCollection<Document> getCollection(String dbName, String collName) { if (null == collName || "".equals(collName)) { return null; } if (null == dbName || "".equals(dbName)) { return null; } MongoCollection<Document> collection = mongoClient.getDatabase(dbName).getCollection(collName); return collection; } /** * 查詢DB下的全部表名 */ public List<String> getAllCollections(String dbName) { MongoIterable<String> colls = getDB(dbName).listCollectionNames(); List<String> _list = new ArrayList<String>(); for (String s : colls) { _list.add(s); } return _list; } /** * 獲取全部數據庫名稱列表 * * @return */ public MongoIterable<String> getAllDBNames() { MongoIterable<String> s = mongoClient.listDatabaseNames(); return s; } /** * 刪除一個數據庫 */ public void dropDB(String dbName) { getDB(dbName).drop(); } /** * 查找對象 - 根據主鍵_id * * @param collection * @param id * @return */ public Document findById(MongoCollection<Document> coll, String id) { ObjectId _idobj = null; try { _idobj = new ObjectId(id); } catch (Exception e) { return null; } Document myDoc = coll.find(Filters.eq("_id", _idobj)).first(); return myDoc; } /** 統計數 */ public int getCount(MongoCollection<Document> coll) { int count = (int) coll.count(); return count; } /** 條件查詢 */ public MongoCursor<Document> find(MongoCollection<Document> coll, Bson filter) { return coll.find(filter).iterator(); } /** 分頁查詢 */ public MongoCursor<Document> findByPage(MongoCollection<Document> coll, Bson filter, int pageNo, int pageSize) { Bson orderBy = new BasicDBObject("_id", 1); return coll.find(filter).sort(orderBy).skip((pageNo - 1) * pageSize).limit(pageSize).iterator(); } /** * 經過ID刪除 * * @param coll * @param id * @return */ public int deleteById(MongoCollection<Document> coll, String id) { int count = 0; ObjectId _id = null; try { _id = new ObjectId(id); } catch (Exception e) { return 0; } Bson filter = Filters.eq("_id", _id); DeleteResult deleteResult = coll.deleteOne(filter); count = (int) deleteResult.getDeletedCount(); return count; } /** * FIXME * * @param coll * @param id * @param newdoc * @return */ public Document updateById(MongoCollection<Document> coll, String id, Document newdoc) { ObjectId _idobj = null; try { _idobj = new ObjectId(id); } catch (Exception e) { return null; } Bson filter = Filters.eq("_id", _idobj); // coll.replaceOne(filter, newdoc); // 徹底替代 coll.updateOne(filter, new Document("$set", newdoc)); return newdoc; } public void dropCollection(String dbName, String collName) { getDB(dbName).getCollection(collName).drop(); } /** * 關閉Mongodb */ public void close() { if (mongoClient != null) { mongoClient.close(); mongoClient = null; } } /** * 測試入口 * * @param args */ public static void main(String[] args) { String dbName = "GC_MAP_DISPLAY_DB"; String collName = "COMMUNITY_BJ"; MongoCollection<Document> coll = MongoDBUtil.instance.getCollection(dbName, collName); // 插入多條 // for (int i = 1; i <= 4; i++) { // Document doc = new Document(); // doc.put("name", "zhoulf"); // doc.put("school", "NEFU" + i); // Document interests = new Document(); // interests.put("game", "game" + i); // interests.put("ball", "ball" + i); // doc.put("interests", interests); // coll.insertOne(doc); // } // // 根據ID查詢 // String id = "556925f34711371df0ddfd4b"; // Document doc = MongoDBUtil2.instance.findById(coll, id); // System.out.println(doc); // 查詢多個 // MongoCursor<Document> cursor1 = coll.find(Filters.eq("name", "zhoulf")).iterator(); // while (cursor1.hasNext()) { // org.bson.Document _doc = (Document) cursor1.next(); // System.out.println(_doc.toString()); // } // cursor1.close(); // 查詢多個 // MongoCursor<Person> cursor2 = coll.find(Person.class).iterator(); // 刪除數據庫 // MongoDBUtil2.instance.dropDB("testdb"); // 刪除表 // MongoDBUtil2.instance.dropCollection(dbName, collName); // 修改數據 // String id = "556949504711371c60601b5a"; // Document newdoc = new Document(); // newdoc.put("name", "時候"); // MongoDBUtil.instance.updateById(coll, id, newdoc); // 統計表 // System.out.println(MongoDBUtil.instance.getCount(coll)); // 查詢全部 Bson filter = Filters.eq("count", 0); MongoDBUtil.instance.find(coll, filter); } }
也請多提寶貴意見和建議。安全