MongoDB 入門教程:開發(fā)環(huán)境搭建及 Node.js 和 Java 的讀寫訪問
MongoDB 是近年來非常流行的一個介于關(guān)系數(shù)據(jù)庫和非關(guān)系數(shù)據(jù)庫之間的解決方案,采取面向文檔的分布式設(shè)計思路,具有強大的可擴展性,表結(jié)構(gòu)自由,并且支持豐富的查詢語句和數(shù)據(jù)類型。時至今日,MongoDB 以其靈活的數(shù)據(jù)存儲方式,逐漸成為 IT 行業(yè)非常流行的一種非關(guān)系型數(shù)據(jù)庫解決方案。
筆者在項目中也經(jīng)歷了從零開始學(xué)習(xí) MongoDB 數(shù)據(jù)庫的過程,因此想把我學(xué)習(xí)過程中的一些心得通過文章分享出來。
步驟1 - MongboDB 環(huán)境搭建
MongoDB 支持的數(shù)據(jù)結(jié)構(gòu)非常松散,是類似 json 的 bson 格式,這種靈活的格式使得 MongoDB 可以存儲比較復(fù)雜的數(shù)據(jù)類型。Mongo 最大的特點是它支持的查詢語言(Query Language)非常強大,其語法有點類似于面向?qū)ο蟮牟樵冋Z言,因此可讀性非常好,并且?guī)缀蹩梢詫崿F(xiàn)類似關(guān)系數(shù)據(jù)庫單表查詢的絕大部分功能。
本步驟介紹 MongoDB 學(xué)習(xí)的第一步:環(huán)境搭建。
從 MongoDB 的 官網(wǎng)下載安裝包。
我安裝在 C 盤的 MyApp 目錄下的 mongoDB,安裝完畢后,bin 文件夾里有好幾個執(zhí)行文件。把 bin 文件路徑加到 windows 系統(tǒng)的環(huán)境變量里。
使用如下命令行啟動 MongoDB 服務(wù)器:
mongod --dbpath C:MyAppmongoDBjerryserverdb
從控制臺打印的 console 里看到下列消息:
Mongo DB starting: pid=16588 port=27017
意思是進程 id 為 16588 的進程啟動了 MongoDB,監(jiān)聽端口號為 27017.
console 里還有其他一些有用的提示,比如:
Read and write access to data and configuration is unrestricted - 沒有對數(shù)據(jù)讀寫設(shè)置權(quán)限
WARNING: This server is bound to localhost - 這個服務(wù)器通過 localhost 訪問
在 cmd 里用命令?netstat -ano | find "27017"
, 發(fā)現(xiàn)確實進程 id 為 16588 的進程在端口 27017 監(jiān)聽:
打開 MongoDB Compass, 這是 MongoDB GUI 圖形化操作界面,在 MongboDB 安裝過程中也自動被安裝了。
Hostname 輸入 localhost,port 輸入 27017,點擊 Connect 進行連接:
連接之后,在 admin 數(shù)據(jù)庫下創(chuàng)建一個新的 Collection:
我的例子里,collection 名稱為 person,點 INSERT DOCUMENT 創(chuàng)建一條記錄, _id 為 MongoDB compass 自動生成的, 另一個字段的名稱為 name, 值為 "Jerry":
再點一次?INSERT DOCUMENT
, 生成兩條 person 記錄。
現(xiàn)在我們新開另一個命令提示行窗口來消費在 MongoDB Compass 里創(chuàng)建的兩條 person 記錄。
命令行?mongo localhost:27017/admin
, 意思是連接這個數(shù)據(jù)庫里的 admin 數(shù)據(jù)庫
此時從前一個啟動 MongoDB 服務(wù)器的命令提示行的控制臺輸出,能看到 connection accepted from 的輸出:
命令行?db.person.find()
, 打印出了 admin 數(shù)據(jù)庫里 person 表里的兩條記錄,說明我們環(huán)境配置成功了。
步驟2 - 使用 Node.js 訪問 MongoDB
在 localhost:27017 的服務(wù)器上,在數(shù)據(jù)庫 admin 下面創(chuàng)建了一個名為 person 的數(shù)據(jù)庫表,并插入了兩條記錄:
上圖是用 MongoDB Compass 查看的成功插入的兩條記錄。
下面我們用 Node.js 讀取這兩條記錄。
首先在命令行里執(zhí)行?npm install mongodb
,
然后新建一個 javaScript 文件,復(fù)制以下內(nèi)容:
注意第 12 行的?dbo.collection("person"). find({}).toArray
,意思是讀取表 person 里的所有記錄。
JavaScript">var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017";
MongoClient.connect(url, function(err, db) {
if (err){
console.log(err);
throw err;
}
console.log("Jerry DB connection established!");
var dbo = db.db("admin");
dbo.collection("person"). find({
}
).toArray(function(err, result) {
if (err)
throw err;
console.log(result);
db.close();
}
);
db.close();
}
);
如果我只想讀取 name 為 Jerry 的那條記錄,只需要把 where 條件傳入方法 find 即可:
從調(diào)試器里能觀察到按照期望的方式被讀取回來了:
步驟3 - 使用 Java 代碼往 MongoDB 里插入數(shù)據(jù)
如果您是基于 Maven 進行依賴管理的 Java 項目,只需要在您的 pom.xml 里加入下面的依賴定義:
org.mongodb
mongodb-driver
3.6.4
然后使用命令行?mvn clean install
?后,您的本地 maven 倉庫里會多出三個和用 Java 連接 MongoDB 相關(guān)的庫:
- bson
- mongodb-driver
- mongodb-driver-core
當(dāng)然也可以手動逐一下載 jar 文件:https://mongodb.github.io/mongo-java-driver/
本文使用的是這三個文件,將它們下載到本地,再加入 Java 項目的 classpath 里。
Java 代碼如下:
package mongoDB;
import java.util.ArrayList;
import java.util.List;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
public class MongoDBTest {
private static void insert(MongoCollection collection) {
Document document = new Document("name", "dog");
List documents = new ArrayList();
documents.add(document);
collection.insertMany(documents);
}
public static void main(String args[]) {
MongoClient mongoClient = null;
try {
mongoClient = new MongoClient("localhost", 27017);
MongoDatabase mongoDatabase = mongoClient.getDatabase("admin");
System.out.println("Connect to database successfully");
MongoCollection collection = mongoDatabase
.getCollection("person");
// insert(collection);
FindIterable findIterable = collection.find();
MongoCursor mongoCursor = findIterable.iterator();
while (mongoCursor.hasNext()) {
System.out.println(mongoCursor.next());
}
}
catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
finally{
mongoClient.close();
}
}
}
和本教程步驟 2相比,上述代碼的 insert 方法里還展示了如何用 Java 代碼給 MongoDB 數(shù)據(jù)庫里增加記錄。
private static void insert(MongoCollection collection) {
Document document = new Document("name", "dog");
List documents = new ArrayList();
documents.add(document);
collection.insertMany(documents);
}
執(zhí)行 Java 應(yīng)用,發(fā)現(xiàn)通過 insert 方法加到數(shù)據(jù)庫的記錄也能被順利讀出來。
總結(jié)
MongoDB 是近年來非常流行的一個介于關(guān)系數(shù)據(jù)庫和非關(guān)系數(shù)據(jù)庫之間的解決方案,采取面向文檔的分布式設(shè)計思路,具有強大的可擴展性,表結(jié)構(gòu)自由,并且支持豐富的查詢語句和數(shù)據(jù)類型。本文首先介紹了 MongoDB 的本地環(huán)境搭建步驟,接著分別介紹了使用 Node.js 和 Java 對本地 MongoDB 進行數(shù)據(jù)讀寫的編程細節(jié)。
版權(quán)聲明:
本站所有文章和圖片均來自用戶分享和網(wǎng)絡(luò)收集,文章和圖片版權(quán)歸原作者及原出處所有,僅供學(xué)習(xí)與參考,請勿用于商業(yè)用途,如果損害了您的權(quán)利,請聯(lián)系網(wǎng)站客服處理。