MongoDB 學習
安裝
windows 系統下的安裝比較簡單,圖省事直接下載 msi 格式的安裝包就行了,安裝嚮導會自動把它安裝成服務的,推薦這樣安裝
也可以手動安裝成服務,以管理員模式啟動 CMD,切換到 MongoDB 的安裝目錄,並執行命令 mongod --dbpath "D:\mongodb\data\db" --logpath "D:\mongodb\logs\log.txt" --install -serviceName "MongoDB"
執行手動安裝命令之前要先把 data/db 和 logs/logs.txt 等資料夾和檔案建立好,不然會報錯。
下面是自動安裝的截圖,最後一步 MongoDB Compass 的勾要去掉,不然要等待下載好久。推薦自己去下載 MongoDB Compass 單獨安裝
通過 net start MongoDB
啟動服務(管理員許可權),一般安裝好會自動啟動的
啟動成功瀏覽器開啟 http://127.0.0.1:27017/
會看到效果
使用
進入到安裝目錄下面的 bin 目錄,裡面有 MongoDB 的工具
為了方便可以把該目錄加到環境變數中,下面是兩個常用的工具
mongo.exe ,MongoDB 命令列工具,可以執行增刪改查等命令
mongodump.exe,備份工具
安裝目錄下面的 data 目錄就是資料庫檔案了。通過命令列新增資料庫和集合會發現檔案的變動,不能辨識
介紹
MongoDB 的資料格式和傳統的關係型資料庫有點差異,不然怎麼會叫 NoSQL 呢
傳統的資料庫,表,記錄對應 MongoDB 中的資料庫,Collection,Document。主要差異就在 Document 上,它是沒有固定結構的一種記錄,和 json 很像,同時 MongoDB 的一些操作語法格式也和 json 的格式很像
命令列
進入到 MongoDB 的安裝目錄,執行 mongo 進入 shell 介面
show dbs 顯示所有的資料庫,及其容量
show collections 顯示所有的集合
use [name] 切換資料庫,沒有也可以切換,在插入資料後會被建立
db.dropDatabase() 刪除資料庫
db.[name].drop() 刪除集合
db.createCollection([name],[options]) 建立集合
db.col.find().pretty() 格式化結果
db.[name].find(query, projection) 查詢,為空列出集合內所有文件
db.[name].insert([json]) 插入文件
db.[name].update() 更新文件
db.[name].save() 替換文件
db.[name].remove() 刪除文件
圖形化介面
有好多款,看了下常用的 Navicate 也有 MongoDB 版本的,不過是收費的
其他的也有好多,不過介面都不怎麼漂亮
我是用的是 MongoDB 官方出的 MongoDB Compass,介面挺漂亮的,關鍵還免費,唯一的缺點是用 Electron 寫的,執行啟動比較慢
在 Java 中使用 MongoDB
先需要驅動程式,jar 包或者 maven.....
這裡使用的是 mongo-java-driver-3.9.1.jar
連線資料庫
如果有設定使用者使用者名稱和密碼
MongoCredential credential = MongoCredential.createCredential("使用者名稱", "資料庫名稱", "密碼".toCharArray()); MongoClient mongoClient = new MongoClient(new ServerAddress("IP", 埠號), Arrays.asList(credential));
沒有設定使用者名稱和密碼,直接連線
private static MongoClient mongoClient; private static MongoDatabase mongoDatabase; public static void main(String[] args) { try { mongoClient = new MongoClient("127.0.0.1", 27017); // 資料庫 mongoDatabase = mongoClient.getDatabase("test"); // collection MongoCollection<Document> collection = mongoDatabase.getCollection("col"); System.out.println(collection.countDocuments()); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); } finally { // 釋放資源 if (mongoClient != null) { mongoClient.close(); } } }
插入
Document doc = new Document(); doc.append("title", "標題"); doc.append("description", "描述"); doc.append("likes", 20); collection.insertOne(doc);
查詢
MongoDB 類似 json 的查詢語法,可以使用 Document 嵌套出相同的格式
當然也提供了 Filters 工具來簡化操作,見下面的刪除操作
// 所有document FindIterable<Document> docs = collection.find(); // 去除_id,description列 docs = docs.projection(new Document("_id", 0).append("description", 0)); // 根據likes升序排列 docs = docs.sort(new Document("likes", 1)); // 遍歷結果,forEach已過時,不推薦使用 MongoCursor<Document> cursor = docs.iterator(); try { while (cursor.hasNext()) { System.out.println(cursor.next().toJson()); } } finally { cursor.close(); }
刪除
刪除 likes 數目小於 50 的 Document
// collection.deleteOne(new Document("likes", new Document("$lt", 50))); collection.deleteOne(Filters.lt("likes", 50));
修改
// 修改一條 collection.updateOne(Filters.eq("title", "標題"), new Document("$set", new Document("title", "新標題"))); // 修改多條,所有點贊數目+1 UpdateResult updateResult = collection.updateMany(new Document(), new Document("$inc", new Document("likes", 1))); System.out.println(updateResult.getModifiedCount());