mongodb通過JAVA 操作
阿新 • • 發佈:2018-11-15
根據 使用 mongodb,總結了一些簡單的操作方法。希望幫助大家。
1.連線 mongodb://根據使用者名稱,密碼進行連線 mongodb 資料庫
public class MongoManager{ private static MongoDatabase mongoDatabase = null; private final static Logger LOGGER = LoggerFactory.getLogger(MongoManager.class); private MongoManager(){} /** * 獲取資料庫連結 * @return Connection */ public static MongoDatabase getMongoDataBase(){ if (mongoDatabase != null) { return mongoDatabase; //如果已經有連線,直接返回,不重新連線! } try { InputStream inStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("mongo.properties"); //通過配置檔案,設定mongodb 連線的引數。獲取當前執行緒的配置檔案!!! Properties properties = new Properties(); properties.load(inStream); String host = properties.getProperty("mongo.host"); int port = Integer.valueOf(properties.getProperty("mongo.port")); String userName = properties.getProperty("mongo.username"); char[] password = properties.getProperty("mongo.password").toCharArray(); String database = properties.getProperty("mongo.database"); //連線到MongoDB服務 如果是遠端連線可以替換“localhost”為伺服器所在IP地址 //ServerAddress()兩個引數分別為 伺服器地址 和 埠 ServerAddress serverAddress = new ServerAddress(host, port); List<ServerAddress> addrs = new ArrayList<ServerAddress>(); addrs.add(serverAddress); //MongoCredential.createScramSha1Credential()三個引數分別為 使用者名稱 資料庫名稱 密碼 MongoCredential credential = MongoCredential.createScramSha1Credential(userName, database, password); List<MongoCredential> credentials = new ArrayList<MongoCredential>(); credentials.add(credential); // MongoClientOptions.Builder build = new MongoClientOptions.Builder(); //與目標資料庫能夠建立的最大connection數量為50 build.connectionsPerHost(50); //如果當前所有的connection都在使用中,則每個connection上可以有50個執行緒排隊等待 build.threadsAllowedToBlockForConnectionMultiplier(50); /* * 一個執行緒訪問資料庫的時候,在成功獲取到一個可用資料庫連線之前的最長等待時間為2分鐘 * 這裡比較危險,如果超過maxWaitTime都沒有獲取到這個連線的話,該執行緒就會丟擲Exception * 故這裡設定的maxWaitTime應該足夠大,以免由於排隊執行緒過多造成的資料庫訪問失敗 */ build.maxWaitTime(1000*60*2); build.connectTimeout(1000*60*1); //與資料庫建立連線的timeout設定為1分鐘 MongoClientOptions mongoClientOptions = build.build(); //通過連線認證獲取MongoDB連線 MongoClient mongoClient = new MongoClient(addrs,credentials,mongoClientOptions); //連線到資料庫 mongoDatabase = mongoClient.getDatabase(database); System.out.println("Connect to mongoDB database successfully"); } catch (Exception e) { LOGGER.error("連線到資料庫失敗",e); } return mongoDatabase; } /** * 關閉資源 * @param mongoDatabase * @param mongoClient */ public static void closeConnection(MongoDatabase mongoDatabase, MongoClient mongoClient){ try { if (mongoDatabase != null) { mongoDatabase = null; } if (mongoClient != null) { mongoClient.close(); //然系統不會回收,只是關閉了,連線存在。 mongoClient = null; } } catch (Exception e) { LOGGER.error(e.getMessage()); } } public static void main( String args[] ){ try{ // 連線到資料庫 getMongoDataBase(); }catch(Exception e){ System.err.println( e.getClass().getName() + ": " + e.getMessage() ); } } }
2. 通過 java 操作 mongodb://部分常見的操作,設定為公共方法呼叫
public class MongoDAO { private final static Logger LOGGER = LoggerFactory.getLogger(MongoDAO.class); private static MongoDatabase mongoDatabase = MongoManager.getMongoDataBase(); private static Map<String,MongoCollection<Document>> collectionMap = new ConcurrentHashMap<>(); private MongoDAO() { } //獲取 mongodb 連線 private static MongoCollection<Document> getCollection(String table){ if(!collectionMap.containsKey(table)){ MongoCollection<Document> mongoCollection = mongoDatabase .getCollection(table); collectionMap.put(table, mongoCollection); } return collectionMap.get(table); } /** * 插入文件(資料記錄行) * * @param table * 資料庫表名 * @param document * 資料記錄行/文件 * @return */ public static String insert(String table, Document document) { try { getCollection(table).insertOne(document); Object id = document.get("_id"); return id != null ? id.toString() : null; } catch (Exception e) { String error = "插入資料失敗!"; LOGGER.error(error, e); } return null; } /** * 查詢文件 * * @param table * 資料庫表名 * @return */ public static MongoCursor<Document> getCollevtion(String table) { try { MongoCollection<Document> mongoCollection = getCollection(table); FindIterable<Document> findIterable = mongoCollection.find(); MongoCursor<Document> mongoCursor = findIterable.iterator(); // while(mongoCursor.hasNext()){ // System.out.println(mongoCursor.next()); // } MongoManager.closeConnection(mongoDatabase, null); return mongoCursor; } catch (Exception e) { LOGGER.error("查詢文件失敗"); } return null; } /** * 更新文件 * * @param table * 資料庫表名 * @param fieldName * 根據某個欄位update,欄位名稱 * @param value * 根據某個欄位update,欄位的值 * @param document * @return */ public static UpdateResult update(String table, String fieldName, Object value, Document document) { try { MongoCollection<Document> mongoCollection = getCollection(table); UpdateResult result = mongoCollection.updateOne( Filters.eq(fieldName, value), document); return result; } catch (Exception e) { LOGGER.error("更新失敗", e); } return null; } /** * 查詢文件 * * @param table * 資料庫表名 * @return */ public static FindIterable<Document> find(String table) { try { MongoCollection<Document> mongoCollection = getCollection(table); FindIterable<Document> findIterable = mongoCollection.find(); return findIterable; } catch (Exception e) { LOGGER.error("查詢失敗", e); } return null; } /** * 根據某個資料欄位名稱和值查詢 * * @param table * 資料庫表名 * @param fieldName * 根據欄位查詢,欄位的名稱 * @param value * 根據欄位查詢,欄位的值 * @return */ public static MongoCursor<Document> findByFiled(String table, String fieldName, Object value) { try { MongoCollection<Document> mongoCollection = getCollection(table); FindIterable<Document> findIterable = mongoCollection.find(Filters .eq(fieldName, value)); MongoCursor<Document> mongoCursor = findIterable.iterator(); return mongoCursor; } catch (Exception e) { LOGGER.error("查詢失敗", e); } return null; } }
3. 通過 java 操作 mongodb --高階操作://根據條件查詢
設定 mongodb 查詢條件:
//設定 mongodb 查詢條件 BasicDBObject basicDBObject = new BasicDBObject(); //查詢條件集合 basicDBObject.put("**", companyId); // == 完全匹配 basicDBObject.put("**", 1); basicDBObject.put("**", 1); Map<String, Object> queryMapContent = new HashMap<>(); queryMapContent.put("$regex", "成功"); // 模糊查詢,包含"$regex" basicDBObject.put("content", new BasicDBObject(queryMapContent)); //時間作為查詢條件 if (StringUtils.isNotEmpty(operateTimeStart) || StringUtils.isNotEmpty(operateTimeEnd)) { Map<String, Object> queryMap = new HashMap<>(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss"); if (StringUtils.isNotEmpty(operateTimeStart)) { Date start = sdf.parse(operateTimeStart); queryMap.put("$gt", start); //起始時間,傳過來時間格式如:yyyy.MM.dd HH:mm:ss } if (StringUtils.isNotEmpty(operateTimeEnd)) { Date end = sdf.parse(operateTimeEnd); queryMap.put("$lt", end); //結束時間 } basicDBObject.put("createTime", new BasicDBObject(queryMap)); } //對集合進行設定 ,存在在集合裡面的值 if (CollectionUtils.isNotEmpty(departmentList)) { Map<String, Object> queryMap = new HashMap<>(); queryMap.put("$in", departmentList); basicDBObject.put("deptId", new BasicDBObject(queryMap)); } if (StringUtils.isNotEmpty(queryName)) { Map<String, Object> queryMap = new HashMap<>(); queryMap.put("$regex", queryName); //模糊查詢,包含 basicDBObject.put("***", new BasicDBObject(queryMap)); } if (StringUtils.isNotEmpty(queryUserName)) { Map<String, Object> queryMap = new HashMap<>(); queryMap.put("$regex", queryUserName); // 模糊查詢,包含 basicDBObject.put("***", new BasicDBObject(queryMap)); }
根據條件查詢:
MongoDatabase mongoDataBase = MongoManager.getMongoDataBase(); //獲取連線
MongoCollection<Document> collection = mongoDataBase.getCollection(LOG_COLLECTION_NAME);
FindIterable<Document> findIterable = collection.find(basicDBObject); //根據上面設定的查詢條件進行查詢。
findIterable = findIterable.sort(new BasicDBObject("createTime",sortNum));//排序 1 為升序排列,而 -1 是用於降序排列。
totalNum = Double.valueOf(collection.count(basicDBObject)); // count 查詢結果有多少條資料
//
findIterable = findIterable.skip(skip).limit(limit); //skip 分頁,從多少條開始取; limit 取多少條資料
MongoCursor<Document> mongoCursor = findIterable.iterator();
while(mongoCursor.hasNext()){
Document document = mongoCursor.next();
LogBean logBean = new LogBean();
int id = document.get("userId") != null ? Integer.parseInt(document.get("userId").toString()) : 0;
SimpleDateFormat sdfData= new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
try { //轉換時間格式:mongodb 時間格式:"createTime" : ISODate("2018-06-11T03:27:21.695Z") ;需要時間格式:2018.07.03 17:02:29
String dateStr = document.get("createTime").toString();
Date date=sdfData.parse(dateStr);
logBean.setLastUpdateTime(date);
} catch (Exception e) {
e.printStackTrace();
LOGGER.error("",e);
}
}
1 為升序排列,而 -1 是用於降序排列。
totalNum = Double.valueOf(collection.count(basicDBObject)); // count 查詢結果有多少條資料
//
findIterable = findIterable.skip(skip).limit(limit); //skip 分頁,從多少條開始取; limit 取多少條資料
MongoCursor<Document> mongoCursor = findIterable.iterator();
while(mongoCursor.hasNext()){
Document document = mongoCursor.next();
LogBean logBean = new LogBean();
int id = document.get("userId") != null ? Integer.parseInt(document.get("userId").toString()) : 0;
SimpleDateFormat sdfData= new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
try { //轉換時間格式:mongodb 時間格式:"createTime" : ISODate("2018-06-11T03:27:21.695Z") ;需要時間格式:2018.07.03 17:02:29
String dateStr = document.get("createTime").toString();
Date date=sdfData.parse(dateStr);
logBean.setLastUpdateTime(date);
} catch (Exception e) {
e.printStackTrace();
LOGGER.error("",e);
}
}
許可權問題:(mongoDB使用者許可權,部署安裝配置 & 命令列操作)
許可權設定參考: https://www.cnblogs.com/xiaoqian1993/p/5944039.html
1. use admin
2.建立使用者
3. 認證使用者
遇見問題及解決方案
error:
> db.createUser({user:”root”,pwd:”root”,roles:[{role:"readWrite",db:”test”}]})
2018-04-24T09:34:03.610+0800 E QUERY [thread1] SyntaxError: illegal character @(shell):1:20
解決方法:修改特殊字元(自己變成那樣的)
error:
使用使用者名稱,密碼連線mongodb。啟動eclipse,過一會報錯:
Timed out after 30000 ms while waiting to connect. Client view of cluster st....
解決方法:是使用者許可權沒設定好,所以連線不成功!
操作 mongodb:
設定啟動配置檔案: 檔名稱: /data/mongodb/conf/mongo.conf
bind_ip = 172.19.160.155
#埠號
port=21707
#資料庫目錄
dbpath=/data/mongodb/data
#日誌目錄
logpath=/data/mongodb/log/mongodb.log
logappend=true
# 是否以守護程序方式執行
fork = true
# 是否以安全認證方式執行,預設是不認證的非安全方式
#noauth = true
auth = true
mongodb /bin 下面啟動檔案: 檔名稱 start.sh 啟動方式 sh start.sh
#!/bin/bash
./mongod -f /data/mongodb/conf/mongo.conf
命令列登入:
[[email protected] bin]# mongo --host 172.19.160.155 --port 21707 //進入命令
>use admin //管理員許可權,admin
> db.auth('admin','123456')
> use tc_trics // tc_trics庫許可權
> db.auth('worker','123456')
show collections