Java操作MongoDB數(shù)據(jù)庫(kù)
除了通過啟動(dòng) mongo 進(jìn)程進(jìn)如 Shell 環(huán)境訪問數(shù)據(jù)庫(kù)外贝润,MongoDB 還提供了其他基于編程語言的訪問數(shù)據(jù)庫(kù)方法。MongoDB 官方提供了 Java 和 Python 語言的驅(qū)動(dòng)包铝宵,利用這些驅(qū)動(dòng)包可使用多種編程方法來連接并操作 MongoDB 數(shù)據(jù)庫(kù)打掘。
介紹一下如何設(shè)置和使用 MongoDB JDBC 驅(qū)動(dòng)程序,通過 JDBC 實(shí)現(xiàn)與 MongoDB 服務(wù)端的通信功能,用戶可以在此基礎(chǔ)上進(jìn)行各種 Java 程序的開發(fā)尊蚁。
安裝 Java 語言驅(qū)動(dòng)包
1) Maven 方式
推薦使用 Maven 的方式管理 MongoDB 的相關(guān)依賴包唯绍,Maven 項(xiàng)目中只需導(dǎo)入如下 pom 依賴包即可:
<dependency>
<groupld>org.mongodb</groupld>
<artifactld>mongodb-driver</artifact1d>
<version>3.4</version>
</dependency>
<dependency>
<groupld>org.mongodb</groupld>
<artifactld>bson</artifactId>
<version>3.4</version>
</dependency>
<dependency>
<groupld>org.mongodb</groupId>
<artifactId>Mongodb-driver-core</artifactld>
<version>3.4</version>
</dependency>
2) 手動(dòng)導(dǎo)入
如果手動(dòng)下載 mongodb-driver,還必須下載其依賴項(xiàng) bson 和 mongodb-driver-core枝誊。在這里需要注意的是况芒,這三個(gè)安裝包需要配合使用,并且版本必須一致叶撒,否則運(yùn)行時(shí)會(huì)報(bào)錯(cuò)绝骚。
首先安裝 MongoDB,本節(jié)實(shí)例為 MongoDB 3.4.2 版本祠够;然后安裝 Java 開發(fā)工具压汪,本節(jié)采用 Eclipse 開發(fā)工具。通過 Github 網(wǎng)站下載驅(qū)動(dòng)包古瓤,分別為 mongodb-driver-3.4.2.jar止剖、mongodb-driver-core-3.4.2.jar、bson-3.4.2.jar落君。
編程實(shí)現(xiàn)
1) import 基礎(chǔ)類庫(kù)
若要完成 MongoDB 的增穿香、刪、改绎速、查等操作皮获,則需要導(dǎo)入很多類庫(kù)。
import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;
import com.mongodb.dient.MongoCollection;
可以根據(jù)編程需要添加必要的類庫(kù)纹冤。
2) 連接數(shù)據(jù)庫(kù)
若要連接數(shù)據(jù)庫(kù)洒宝,則需要指定數(shù)據(jù)庫(kù)名稱。如果數(shù)據(jù)庫(kù)不存在萌京,則 MongoDB 會(huì)自動(dòng)創(chuàng)建數(shù)據(jù)庫(kù)雁歌。如下代碼實(shí)現(xiàn)了簡(jiǎn)易的數(shù)據(jù)庫(kù)連接:
public class App {
public static void main(String[] args) {
try {
//連接MongoDB服務(wù)器,端口號(hào)為27017
MongoClient mongoClient = new MongoClient("localhost", 27017);
//連接數(shù)據(jù)庫(kù)
MongoDatabase mDatabase = mongoClient.getDatabase("test"); //test可選
System.out.printin("Connect to database successfully!");
System.out.printIn("MongoDatabase inof is : "+mDatabase.getName());
} catch (Exception e) {
System.err.printIn(e.getClass().getName() + ": " + e.getMessage());
}
}
}
3) 切換至集合
連接至具體數(shù)據(jù)庫(kù)以后知残,使用以下代碼切換到集合靠瞎,如果集合不存在,則使用如下代碼新建集合:
MongoCollection collection = database.getCollection("myTestCollection");
4) 插入文檔
切換至集合后橡庞,就可以進(jìn)行文檔的增较坛、刪、改扒最、查操作丑勤。首先定義文檔,并使用 append吧趣。方法追加內(nèi)容法竞,代碼如下:
Document document = new Document("_id", 1999)
.append("title", "MongoDB Insert Demo")
.append("description","database")
.append("likes", 30)
.append("by", "demo point")
.append("url", "http://c.biancheng.net/mongodb/");
document 為 BSON 類型的文檔耙厚,實(shí)際上為一個(gè)列表,每項(xiàng)有兩個(gè)元素岔霸,即字段名和值薛躬。
文檔定義完成后,再使用 insertOne 方法將此文檔插入集合:
collection.insertOne(document);
如果插入多條數(shù)據(jù)呆细,需要先定義一個(gè) Document 列表型宝,然后用 add() 方法添加多個(gè) Document 元素,最后用 insertMany() 方法插入絮爷,代碼如下:
List<Document> documents = new ArrayList<Document>();documents.add(document1);collection.insertMany(documents);
5) 刪除文檔
使用 delete() 方法刪除一個(gè)或多個(gè)文檔趴酣,代碼如下:
collection.deleteOne(document);collection.deleteMany(new Document ("likes", 30));
6) 更新數(shù)據(jù)
使用 updataOne() 方法更新一條數(shù)據(jù)或多個(gè)數(shù)據(jù),代碼如下:
collection.updataOne (eq ("likes", 30), new Document ("$set", new Document ("likes", 50)));java
updateOne() 方法中有兩個(gè)參數(shù)坑夯,第一個(gè)參數(shù)表示更新的內(nèi)容等于 ("likes",30) 的文檔岖寞,第二個(gè)參數(shù)為要修改的內(nèi)容,使用 $set 參數(shù)修改當(dāng)前值柜蜈,修改的內(nèi)容為 ("likes", 50)仗谆。
7) 查詢數(shù)據(jù)
利用游標(biāo)類型實(shí)現(xiàn)數(shù)據(jù)的查詢和遍歷顯示,使用游標(biāo)前需要 import MongoCursor 類庫(kù)淑履。
import com.mongodb.client.MongoCursor;
document Doc = (Document)collection.find(eq("likes", 30)).iterator();
MongoCursor<Document> cursor =collection.find().iterator();
try{
while (cursor.hasNext()){
System.out.printin(cursor.next().toJson());
}
} finally{
Cursor.close();
}
設(shè)置 find() 方法的參數(shù)為查詢條件隶垮,參數(shù)為比較的 Document 元素。
8) 其他方法
刪除數(shù)據(jù)庫(kù)或集合鳖谈,代碼如下:
mDatabase.drop();collection.drop();
關(guān)閉客戶端連接岁疼,代碼如下:
mongoClient.close();