JAVA 操作mongo

                // 查詢所有+
// 或條件
Bson star = Filters.or(Filters.eq("emali", "[email protected]"), Filters.eq("zijin", "300 萬人民幣"));
// 或條件
Bson money = Filters.or(Filters.eq("companyType", "物流"), Filters.eq("rongzi", "已認證"));
// 全匹配
Bson allQuery = Filters.regex("address", "西安市未");
// 左匹配
Bson liftQuery = Filters.regex("address", "^地址:西安市未");
// 右匹配
Bson rightQuery = Filters.regex("legal_person", "帥$");
Bson starQuery = Filters.eq("time", 13);
Bson query = Filters.and(starQuery);

package com.LEO.automation.company.dao;



import java.util.ArrayList;
import java.util.List;


import org.apache.log4j.Logger;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.bson.types.ObjectId;


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;
import com.mongodb.client.result.UpdateResult;


import cn.freecubs.freestruts.framework.action.annex.Paging;
import cn.freecubs.freestruts.framework.tool.PropertyParam;


public enum MongoTemplate {


/**
* 定義一個枚舉的元素,它代表此類的一個實例
*/
instance;


// 從配置文件中獲取屬性值
private static String host = PropertyParam.getInstance().getValue("mongo.host");
private static int port = Integer.valueOf(PropertyParam.getInstance().getValue("mongo.port"));
private static String dbName = PropertyParam.getInstance().getValue("mongo.dbName");
private static String collName = PropertyParam.getInstance().getValue("mongo.collName");
private static MongoClient mongoClient;
private static MongoCollection<Document> coll = null;
private Logger logger = Logger.getLogger(MongoTemplate.class);
static {
mongoClient = new MongoClient(host, port);
// 大部分用戶使用mongodb都在安全內網下,但如果將mongodb設爲安全驗證模式,就需要在客戶端提供用戶名和密碼:
// boolean auth = db.authenticate(myUserName, myPassword);
Builder options = new MongoClientOptions.Builder();
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();


// 爲空判斷
dbName = dbName == null || "".equals(dbName) ? "localCompany" : dbName;
collName = collName == null || "".equals(collName) ? "localCompany" : collName;
coll = mongoClient.getDatabase(dbName).getCollection(collName);
}


// ------------------------------------共用方法---------------------------------------------------
/**
* 獲取DB實例 - 指定DB

* @param dbName
* @return
*/
public MongoDatabase getDB(String dbName) {
if (dbName != null && !"".equals(dbName)) {
MongoDatabase database = mongoClient.getDatabase(dbName);
return database;
}
return null;
}


/**
* 查詢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(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;
}


/**
* 統計條數

* @param query
* @return
*/
public int getCount(Bson query) {
int count = 0;
if (query == null) {
count = (int) coll.count();
} else {
count = (int) coll.count(query);
}
return count;
}


/**
* 按照條件查詢第一條數據

* @param filter
* @return
*/
public Document findOneByQuery(Bson filter) {
return coll.find(filter).first();
}


/**
* 條件查詢全部數據

* @param filter
* @return
*/
public List<String> findAll(Bson filter) {
return cur2List(coll.find(filter).iterator());
}


/**
* 條件查詢

* @param filter
* @return
*/
public List<String> findByFiltersCount(Bson filter, int count) {
if (count < 0) {
count = 0;
}
return cur2List(coll.find(filter).limit(count).iterator());
}


/**
* 分頁查詢

* @param filter
* @param page
* @param orderBy
* @return
*/
public List<String> findByPage(Bson filter, Paging page, Bson orderBy) {


// 添加頁數
if (page.getRowsCount() == 0) {
page.setRowsCount(instance.getCount(filter));
}


MongoCursor<Document> cur = null;
if (filter != null) {
if (orderBy == null) {
cur = coll.find(filter).skip(page.getSkip()).limit(page.getRowsPerPage()).iterator();
} else {
cur = coll.find(filter).sort(orderBy).skip(page.getSkip()).limit(page.getRowsPerPage()).iterator();
}
} else {
if (orderBy == null) {
cur = coll.find().skip(page.getSkip()).limit(page.getRowsPerPage()).iterator();
} else {
cur = coll.find().sort(orderBy).skip(page.getSkip()).limit(page.getRowsPerPage()).iterator();
}
}
return cur2List(cur);
}


/**
* 數據庫油標數據轉成字符串list

* @param cur
* @return
*/
private List<String> cur2List(MongoCursor<Document> cur) {
List<String> listData = new ArrayList<>();
while (cur.hasNext()) {
listData.add(cur.next().toJson());
}
return listData;
}


/**
* 通過ID刪除

* @param coll
* @param id
* @return
*/
public int deleteById(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(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 updataInfo(Document newdoc) {
try {
ObjectId _id = new ObjectId(newdoc.get("id") + "");
Bson filter = Filters.eq("_id", _id);
UpdateResult result = coll.updateOne(filter, new Document("$set", newdoc));
this.logger.info(String.format("MongoTemplate:根據id更新結果%s", result.toString()));
} catch (Exception e) {
Object objectId = newdoc.get("_id");
if (objectId != null) {
ObjectId _id = new ObjectId(objectId + "");
Bson filter = Filters.eq("_id", _id);
UpdateResult result = coll.updateOne(filter, new Document("$set", newdoc));
this.logger.info(String.format("MongoTemplate:根據id更新結果%s", result.toString()));
} else {
String companyName = newdoc.get("companyName") + "";
Bson filter = Filters.eq("companyName", companyName);
UpdateResult result = coll.updateOne(filter, new Document("$set", newdoc));
this.logger.info(String.format("MongoTemplate:根據companyName更新結果%s", result.toString()));
}
}
}


/**
* 保存一條數據

* @param newdoc
* @return
*/
public Document save(Document newdoc) {
try {
coll.insertOne(newdoc);
} catch (Exception e) {
String name = newdoc.getString("companyName");
// Bson filter = Filters.eq("_id", name);
Bson filter = Filters.eq("companyName", name);
newdoc.remove("_id");
UpdateResult result = coll.updateOne(filter, new Document("$set", newdoc));
this.logger.info(String.format("MongoTemplate:根據id更新結果%s", result.toString()));
}
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;
}
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章