java mongodb常用工具類
阿新 • • 發佈:2018-12-24
//http://blog.csdn.net/ceclar123/article/details/50516535
public class MongoDBDaoImpl {
/**
* MongoClient的例項代表資料庫連線池,是執行緒安全的,可以被多執行緒共享,客戶端在多執行緒條件下僅維持一個例項即可
* Mongo是非執行緒安全的,目前mongodb API中已經建議用MongoClient替代Mongo
*/
private MongoClient mongoClient = null;
/**
* 構造方法
*
* @param ip 127.0.0.1
* @param port 27107
*/
private MongoDBDaoImpl(String ip, int port) {
if (mongoClient == null) {
MongoClientOptions.Builder build = new MongoClientOptions.Builder();
/*
* 一個執行緒訪問資料庫的時候,在成功獲取到一個可用資料庫連線之前的最長等待時間為2分鐘
* 這裡比較危險,如果超過maxWaitTime都沒有獲取到這個連線的話,該執行緒就會丟擲Exception
* 故這裡設定的maxWaitTime應該足夠大,以免由於排隊執行緒過多造成的資料庫訪問失敗
*/
build.maxWaitTime(1000 * 60 * 2);
build.connectTimeout(1000 * 60 * 1); //與資料庫建立連線的timeout設定為1分鐘
build.socketTimeout(0);// 套接字超時時間,0無限制
build.connectionsPerHost(300); //連線池設定為300個連線,預設為100
build.threadsAllowedToBlockForConnectionMultiplier(5000);// 執行緒佇列數,如果連線執行緒排滿了佇列就會丟擲“Out of semaphores to get db”錯誤。
build.writeConcern(WriteConcern.ACKNOWLEDGED);
MongoClientOptions myOptions = build.build();
try {
//資料庫連線例項
mongoClient = new MongoClient(new ServerAddress(ip, port), myOptions);
} catch (MongoException e) {
e.printStackTrace();
}
}
}
private static MongoDBDaoImpl mongoDBDaoImpl = null;
/**
* 獲取例項
*
* @param ip 127.0.0.1
* @param port 27107
* @return
*/
public synchronized static MongoDBDaoImpl getInstance(String ip, int port) {
if (mongoDBDaoImpl == null) {
mongoDBDaoImpl = new MongoDBDaoImpl(ip, port);
}
return mongoDBDaoImpl;
}
public boolean isExits(String dbName, String collectionName, Map<String, Object> filterMap) {
if (filterMap != null) {
FindIterable<Document> docs = mongoClient.getDatabase(dbName).getCollection(collectionName).find(new Document(filterMap));
Document doc = docs.first();
if (doc != null) {
return true;
} else {
return false;
}
}
return false;
}
public boolean insert(String dbName, String collectionName, Map<String, Object> insertMap) {
if (insertMap != null) {
mongoClient.getDatabase(dbName).getCollection(collectionName).insertOne(new Document(insertMap));
return true;
}
return false;
}
public boolean deleteById(String dbName, String collectionName, String _id) {
ObjectId objectId = new ObjectId(_id);
Bson filter = Filters.eq("_id", objectId);
DeleteResult deleteResult = getDatabase(dbName).getCollection(collectionName).deleteOne(filter);
long deletedCount = deleteResult.getDeletedCount();
return deletedCount > 0 ? true : false;
}
public boolean delete(String dbName, String collectionName, Map<String, Object> map) {
if (map != null) {
DeleteResult result = mongoClient.getDatabase(dbName).getCollection(collectionName).deleteMany(new Document(map));
long deletedCount = result.getDeletedCount();
return deletedCount > 0 ? true : false;
}
return false;
}
public boolean updateOne(String dbName, String collectionName, Map<String, Object> filterMap, Map<String, Object> updateMap) {
if (filterMap != null && filterMap.size() > 0 && updateMap != null) {
UpdateResult result = mongoClient.getDatabase(dbName).getCollection(collectionName).updateOne(new Document(filterMap), new Document("$set", new Document(updateMap)));
long modifiedCount = result.getModifiedCount();
return modifiedCount > 0 ? true : false;
}
return false;
}
public boolean updateById(String dbName, String collectionName, String _id, Document updateDoc) {
ObjectId objectId = new ObjectId(_id);
Bson filter = Filters.eq("_id", objectId);
UpdateResult result = getDatabase(dbName).getCollection(collectionName).updateOne(filter, new Document("$set", updateDoc));
long modifiedCount = result.getModifiedCount();
return modifiedCount > 0 ? true : false;
}
public List<Document> find(String dbName, String collectionName, Bson filter) {
List<Document> resultList = new ArrayList<Document>();
if (filter != null) {
FindIterable<Document> docs = mongoClient.getDatabase(dbName).getCollection(collectionName).find(filter);
docs.forEach(new Block<Document>() {
public void apply(Document document) {
resultList.add(document);
}
});
}
return resultList;
}
public Document findById(String dbName, String collectionName, String _id) {
ObjectId objectId = new ObjectId(_id);
Document doc = getDatabase(dbName).getCollection(collectionName).find(Filters.eq("_id", objectId)).first();
return doc;
}
/**
* 分頁查詢
*
* @param dbName
* @param collectionName
* @param filter
* @param pageIndex 從1開始
* @param pageSize
* @return
*/
public List<Document> findByPage(String dbName, String collectionName, Bson filter, int pageIndex, int pageSize) {
Bson orderBy = new BasicDBObject("_id", 1);
List<Document> resultList = new ArrayList<Document>();
FindIterable<Document> docs = getDatabase(dbName).getCollection(collectionName).find(filter).sort(orderBy).skip((pageIndex - 1) * pageSize).limit(pageSize);
docs.forEach(new Block<Document>() {
public void apply(Document document) {
resultList.add(document);
}
});
return resultList;
}
public MongoCollection getCollection(String dbName, String collectionName) {
return mongoClient.getDatabase(dbName).getCollection(collectionName);
}
public MongoDatabase getDatabase(String dbName) {
return mongoClient.getDatabase(dbName);
}
public long getCount(String dbName, String collectionName) {
return getDatabase(dbName).getCollection(collectionName).count();
}
/**
* 查詢dbName下的所有表名
*
* @param dbName
* @return
*/
public List<String> getAllCollections(String dbName) {
MongoIterable<String> cols = getDatabase(dbName).listCollectionNames();
List<String> _list = new ArrayList<String>();
for (String s : cols) {
_list.add(s);
}
return _list;
}
/**
* 獲取所有資料庫名稱列表
*
* @return
*/
public MongoIterable<String> getAllDatabaseName() {
MongoIterable<String> s = mongoClient.listDatabaseNames();
return s;
}
/**
* 刪除一個數據庫
*
* @param dbName
*/
public void dropDatabase(String dbName) {
getDatabase(dbName).drop();
}
/**
* 刪除collection
*
* @param dbName
* @param collectionName
*/
public void dropCollection(String dbName, String collectionName) {
getDatabase(dbName).getCollection(collectionName).drop();
}
public void close() {
if (mongoClient != null) {
mongoClient.close();
mongoClient = null;
}
}
}
public class MongoDBDaoImpl {
/**
* MongoClient的例項代表資料庫連線池,是執行緒安全的,可以被多執行緒共享,客戶端在多執行緒條件下僅維持一個例項即可
* Mongo是非執行緒安全的,目前mongodb API中已經建議用MongoClient替代Mongo
*/
private MongoClient mongoClient = null;
/**
* 構造方法
*
* @param ip 127.0.0.1
* @param port 27107
*/
private MongoDBDaoImpl(String ip, int port) {
if (mongoClient == null) {
MongoClientOptions.Builder build = new MongoClientOptions.Builder();
/*
* 一個執行緒訪問資料庫的時候,在成功獲取到一個可用資料庫連線之前的最長等待時間為2分鐘
* 這裡比較危險,如果超過maxWaitTime都沒有獲取到這個連線的話,該執行緒就會丟擲Exception
* 故這裡設定的maxWaitTime應該足夠大,以免由於排隊執行緒過多造成的資料庫訪問失敗
*/
build.maxWaitTime(1000 * 60 * 2);
build.connectTimeout(1000 * 60 * 1); //與資料庫建立連線的timeout設定為1分鐘
build.socketTimeout(0);// 套接字超時時間,0無限制
build.connectionsPerHost(300); //連線池設定為300個連線,預設為100
build.threadsAllowedToBlockForConnectionMultiplier(5000);// 執行緒佇列數,如果連線執行緒排滿了佇列就會丟擲“Out of semaphores to get db”錯誤。
build.writeConcern(WriteConcern.ACKNOWLEDGED);
MongoClientOptions myOptions = build.build();
try {
//資料庫連線例項
mongoClient = new MongoClient(new ServerAddress(ip, port), myOptions);
} catch (MongoException e) {
e.printStackTrace();
}
}
}
private static MongoDBDaoImpl mongoDBDaoImpl = null;
/**
* 獲取例項
*
* @param ip 127.0.0.1
* @param port 27107
* @return
*/
public synchronized static MongoDBDaoImpl getInstance(String ip, int port) {
if (mongoDBDaoImpl == null) {
mongoDBDaoImpl = new MongoDBDaoImpl(ip, port);
}
return mongoDBDaoImpl;
}
public boolean isExits(String dbName, String collectionName, Map<String, Object> filterMap) {
if (filterMap != null) {
FindIterable<Document> docs = mongoClient.getDatabase(dbName).getCollection(collectionName).find(new Document(filterMap));
Document doc = docs.first();
if (doc != null) {
return true;
} else {
return false;
}
}
return false;
}
public boolean insert(String dbName, String collectionName, Map<String, Object> insertMap) {
if (insertMap != null) {
mongoClient.getDatabase(dbName).getCollection(collectionName).insertOne(new Document(insertMap));
return true;
}
return false;
}
public boolean deleteById(String dbName, String collectionName, String _id) {
ObjectId objectId = new ObjectId(_id);
Bson filter = Filters.eq("_id", objectId);
DeleteResult deleteResult = getDatabase(dbName).getCollection(collectionName).deleteOne(filter);
long deletedCount = deleteResult.getDeletedCount();
return deletedCount > 0 ? true : false;
}
public boolean delete(String dbName, String collectionName, Map<String, Object> map) {
if (map != null) {
DeleteResult result = mongoClient.getDatabase(dbName).getCollection(collectionName).deleteMany(new Document(map));
long deletedCount = result.getDeletedCount();
return deletedCount > 0 ? true : false;
}
return false;
}
public boolean updateOne(String dbName, String collectionName, Map<String, Object> filterMap, Map<String, Object> updateMap) {
if (filterMap != null && filterMap.size() > 0 && updateMap != null) {
UpdateResult result = mongoClient.getDatabase(dbName).getCollection(collectionName).updateOne(new Document(filterMap), new Document("$set", new Document(updateMap)));
long modifiedCount = result.getModifiedCount();
return modifiedCount > 0 ? true : false;
}
return false;
}
public boolean updateById(String dbName, String collectionName, String _id, Document updateDoc) {
ObjectId objectId = new ObjectId(_id);
Bson filter = Filters.eq("_id", objectId);
UpdateResult result = getDatabase(dbName).getCollection(collectionName).updateOne(filter, new Document("$set", updateDoc));
long modifiedCount = result.getModifiedCount();
return modifiedCount > 0 ? true : false;
}
public List<Document> find(String dbName, String collectionName, Bson filter) {
List<Document> resultList = new ArrayList<Document>();
if (filter != null) {
FindIterable<Document> docs = mongoClient.getDatabase(dbName).getCollection(collectionName).find(filter);
docs.forEach(new Block<Document>() {
public void apply(Document document) {
resultList.add(document);
}
});
}
return resultList;
}
public Document findById(String dbName, String collectionName, String _id) {
ObjectId objectId = new ObjectId(_id);
Document doc = getDatabase(dbName).getCollection(collectionName).find(Filters.eq("_id", objectId)).first();
return doc;
}
/**
* 分頁查詢
*
* @param dbName
* @param collectionName
* @param filter
* @param pageIndex 從1開始
* @param pageSize
* @return
*/
public List<Document> findByPage(String dbName, String collectionName, Bson filter, int pageIndex, int pageSize) {
Bson orderBy = new BasicDBObject("_id", 1);
List<Document> resultList = new ArrayList<Document>();
FindIterable<Document> docs = getDatabase(dbName).getCollection(collectionName).find(filter).sort(orderBy).skip((pageIndex - 1) * pageSize).limit(pageSize);
docs.forEach(new Block<Document>() {
public void apply(Document document) {
resultList.add(document);
}
});
return resultList;
}
public MongoCollection getCollection(String dbName, String collectionName) {
return mongoClient.getDatabase(dbName).getCollection(collectionName);
}
public MongoDatabase getDatabase(String dbName) {
return mongoClient.getDatabase(dbName);
}
public long getCount(String dbName, String collectionName) {
return getDatabase(dbName).getCollection(collectionName).count();
}
/**
* 查詢dbName下的所有表名
*
* @param dbName
* @return
*/
public List<String> getAllCollections(String dbName) {
MongoIterable<String> cols = getDatabase(dbName).listCollectionNames();
List<String> _list = new ArrayList<String>();
for (String s : cols) {
_list.add(s);
}
return _list;
}
/**
* 獲取所有資料庫名稱列表
*
* @return
*/
public MongoIterable<String> getAllDatabaseName() {
MongoIterable<String> s = mongoClient.listDatabaseNames();
return s;
}
/**
* 刪除一個數據庫
*
* @param dbName
*/
public void dropDatabase(String dbName) {
getDatabase(dbName).drop();
}
/**
* 刪除collection
*
* @param dbName
* @param collectionName
*/
public void dropCollection(String dbName, String collectionName) {
getDatabase(dbName).getCollection(collectionName).drop();
}
public void close() {
if (mongoClient != null) {
mongoClient.close();
mongoClient = null;
}
}
}