package com.mongodb; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.bson.Document; import org.bson.conversions.Bson; import org.bson.types.ObjectId; import org.slf4j.Logger; import org.slf4j.LoggerFactory; 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 連接工具類 做者:qinxuewu 時間:2015年8月15日下午6:02:09 */ public class MongoDBUtil { private static MongoClient mongoClient; private static Logger logger = LoggerFactory.getLogger(MongoDBUtil.class); static { logger.info("===============MongoDBUtil初始化========================"); mongoClient = new MongoClient("localhost", 27017); // 大部分用戶使用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無限制 // 線程隊列數,若是鏈接線程排滿了隊列就會拋出「Out of semaphores to get db」錯誤。 options.threadsAllowedToBlockForConnectionMultiplier(5000); options.writeConcern(WriteConcern.SAFE); options.build(); } /** * 獲取DB實例 - 指定DB * * @param dbName * @return */ public static MongoDatabase getDB(String dbName) { if (dbName != null && !"".equals(dbName)) { MongoDatabase database = mongoClient.getDatabase(dbName); return database; } return null; } /** * 獲取collection對象 - 指定Collection * * @param collName * @return */ public static 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 static 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 static MongoIterable<String> getAllDBNames() { MongoIterable<String> s = mongoClient.listDatabaseNames(); return s; } /** * 刪除一個數據庫 */ public static void dropDB(String dbName) { getDB(dbName).drop(); } /*** * 刪除文檔 * * @param dbName * @param collName */ public static void dropCollection(String dbName, String collName) { getDB(dbName).getCollection(collName).drop(); } /** * 查找對象 - 根據主鍵_id * * @param collection * @param id * @return */ public static Document findById(MongoCollection<Document> coll, String id) { try { ObjectId _id = null; try { _id = new ObjectId(id); } catch (Exception e) { return null; } Document myDoc = coll.find(Filters.eq("_id", _id)).first(); return myDoc; } catch (Exception e) { e.printStackTrace(); close(); } return null; } /*** * 條件查詢對象 * @param coll * @param filter * @return */ public static Document findByNames(MongoCollection<Document> coll, Bson filter) { try { return coll.find(filter).first(); } catch (Exception e) { e.printStackTrace(); close(); } return null; } /*** * 多條件查詢對象 * @param coll * @param filter * @return */ public static Document findByNames(MongoCollection<Document> coll,Map<String, Object> map) { try { return coll.find(new BasicDBObject(map)).first(); } catch (Exception e) { e.printStackTrace(); close(); } return null; } /** 統計數 */ public static int getCount(MongoCollection<Document> coll) { try { int count = (int) coll.count(); return count; } catch (Exception e) { e.printStackTrace(); close(); } return 0; } /** 查詢 多個集合文檔*/ public static MongoCursor<Document> find(MongoCollection<Document> coll, Bson filter) { try { return coll.find(filter).iterator(); } catch (Exception e) { e.printStackTrace(); close(); } return null; } /** * map集合 多條件查詢 * @param coll * @param map * @return */ public static MongoCursor<Document> find(MongoCollection<Document> coll, Map<String, Object> map) { try { return coll.find(new BasicDBObject(map)).iterator(); } catch (Exception e) { e.printStackTrace(); close(); } return null; } /*** * 分頁查詢 默認按_id字段降序 * @param coll * @param map * @param pageNo * @param pageSize * @return */ public static MongoCursor<Document> findByPage(MongoCollection<Document> coll, Map<String, Object> map, int pageNo, int pageSize){ try { Bson orderBy = new BasicDBObject("_id", -1); return coll.find(new BasicDBObject(map)).sort(orderBy).skip((pageNo - 1) * pageSize).limit(pageSize).iterator(); } catch (Exception e) { e.printStackTrace(); close(); } return null; } /** * 分頁查詢 自定義排序 * @param coll * @param sorting * @param name * @param map * @param pageNo * @param pageSize * @return */ public static MongoCursor<Document> findByPage(MongoCollection<Document> coll,String sorting,String name, Map<String, Object> map, int pageNo, int pageSize){ try { Bson orderBy=null; //降序 if(sorting.equals("desc")){ orderBy= new BasicDBObject(name, -1); }else{ orderBy= new BasicDBObject(name, 1); } return coll.find(new BasicDBObject(map)).sort(orderBy).skip((pageNo - 1) * pageSize).limit(pageSize).iterator(); } catch (Exception e) { e.printStackTrace(); close(); } return null; } /** * 經過ID刪除 * * @param coll * @param id * @return */ public static int deleteById(MongoCollection<Document> coll, String id) { try { int count = 0; ObjectId _id = null; _id = new ObjectId(id); Bson filter = Filters.eq("_id", _id); DeleteResult deleteResult = coll.deleteOne(filter); count = (int) deleteResult.getDeletedCount(); return count; } catch (Exception e) { e.printStackTrace(); close(); } return 0; } /** * 修改 * * @param coll * @param id * @param newdoc * @return */ public static Document updateById(MongoCollection<Document> coll, String id, Document newdoc) { ObjectId _idobj = null; try { _idobj = new ObjectId(id); Bson filter = Filters.eq("_id", _idobj); // coll.replaceOne(filter, newdoc); // 徹底替代 coll.updateOne(filter, new Document("$set", newdoc)); return newdoc; } catch (Exception e) { e.printStackTrace(); close(); } return null; } /** * 添加 * @param coll * @param doc * @return */ public static boolean save(MongoCollection<Document> coll,Document doc){ boolean falg=false; try { coll.insertOne(doc); falg=true; } catch (Exception e) { e.printStackTrace(); logger.error("添加異常,異常信息:", e); }finally{ close(); } return falg; } /** * 關閉Mongodb */ public static void close() { if (mongoClient != null) { mongoClient.close(); mongoClient = null; } } public static void main(String[] args) { MongoCollection<Document> list = getCollection("mydb", "users"); Document d = list.find().first(); System.out.println("userid====" + d.get("userid")); System.out.println(d); } }