java連線mongoDB 並進行增刪改查操作
1、安裝 MongoDB JDBC驅動程式
在java中使用mongoDB之前,首先需要擁有java連線mongoDB的第三方驅動包(jar包)
1)maven專案可通過在pom.xml中新增依賴
<dependencies> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>3.0.4</version> </dependency> </dependencies>
2)非maven專案jar包下載地址:
2、連線資料庫
將mongoDB JDBC驅動加入到專案之後,就可以對mongoDB進行操作了。
1)不通過認證連線mongoDB服務
//連線到 mongodb 服務
MongoClient mongoClient = new MongoClient("localhost", 27017);
這裡的 "localhost" 表示連線的伺服器地址,27017 為埠號。可以省略 埠號 不寫,系統將預設埠號為 27017。如:
//連線到 mongodb 服務,預設埠號為27017 MongoClient mongoClient = new MongoClient("localhost");
也可以將 伺服器地址 和 埠號 都省略,系統預設伺服器地址為 "localhost",埠號為27017。如:
//連線到 mongodb 服務,預設連線到localhost伺服器,埠號為27017
MongoClient mongoClient = new MongoClient();
2)通過認證連線mongoDB服務
List<ServerAddress> adds = new ArrayList<>(); //ServerAddress()兩個引數分別為 伺服器地址 和 埠 ServerAddress serverAddress = new ServerAddress("localhost", 27017); adds.add(serverAddress); List<MongoCredential> credentials = new ArrayList<>(); //MongoCredential.createScramSha1Credential()三個引數分別為 使用者名稱 資料庫名稱 密碼 MongoCredential mongoCredential = MongoCredential.createScramSha1Credential("username", "databaseName", "password".toCharArray()); credentials.add(mongoCredential); //通過連線認證獲取MongoDB連線 MongoClient mongoClient = new MongoClient(adds, credentials);
ServerAddress()兩個引數 "localhost" , 27017 分別為 伺服器地址 和 埠。
MongoCredential.createScramSha1Credential()三個引數 "username", "databaseName", "password".toCharArray() 分別為 使用者名稱 資料庫名稱 密碼。
3)連線到資料庫
//連線到資料庫
MongoDatabase mongoDatabase = mongoClient.getDatabase("test");
這裡的 "test" 表示資料庫名,若指定的資料庫不存在,mongoDB將會在你第一次插入文件時建立資料庫。
4)封裝成工具類
由於所有連線資料庫操作都需要執行這兩步操作,我們可以將這兩步操作封裝成工具類。
import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;
//mongodb 連線資料庫工具類
public class MongoDBUtil {
//不通過認證獲取連線資料庫物件
public static MongoDatabase getConnect(){
//連線到 mongodb 服務
MongoClient mongoClient = new MongoClient("localhost", 27017);
//連線到資料庫
MongoDatabase mongoDatabase = mongoClient.getDatabase("test");
//返回連線資料庫物件
return mongoDatabase;
}
//需要密碼認證方式連線
public static MongoDatabase getConnect2(){
List<ServerAddress> adds = new ArrayList<>();
//ServerAddress()兩個引數分別為 伺服器地址 和 埠
ServerAddress serverAddress = new ServerAddress("localhost", 27017);
adds.add(serverAddress);
List<MongoCredential> credentials = new ArrayList<>();
//MongoCredential.createScramSha1Credential()三個引數分別為 使用者名稱 資料庫名稱 密碼
MongoCredential mongoCredential = MongoCredential.createScramSha1Credential("username", "databaseName", "password".toCharArray());
credentials.add(mongoCredential);
//通過連線認證獲取MongoDB連線
MongoClient mongoClient = new MongoClient(adds, credentials);
//連線到資料庫
MongoDatabase mongoDatabase = mongoClient.getDatabase("test");
//返回連線資料庫物件
return mongoDatabase;
}
}
3、對資料庫進行CRUD
mongoDB中的資料都是通過文件(對應於關係型資料庫表中的一行)儲存的,而文件又儲存在集合(對應於關係型資料庫的表)中。
1)獲取集合
要對資料進行CRUD操作首先要獲取到操作的集合。
//獲取集合
MongoCollection<Document> collection = MongoDBUtil.getConnect().getCollection("user");
這裡的 "user" 表示集合的名字,如果指定的集合不存在,mongoDB將會在你第一次插入文件時建立集合。
2)建立文件
要插入文件首先需要建立文件物件
//建立文件
Document document = new Document("name","張三")
.append("sex", "男")
.append("age", 18);
3)插入文件
插入一個文件,使用 MongoCollection 物件的 insertOne() 方法,該方法接收一個 Document 物件作為要插入的資料
//插入一個文件
@Test
public void insertOneTest(){
//獲取資料庫連線物件
MongoDatabase mongoDatabase = MongoDBUtil.getConnect();
//獲取集合
MongoCollection<Document> collection = mongoDatabase.getCollection("user");
//要插入的資料
Document document = new Document("name","張三")
.append("sex", "男")
.append("age", 18);
//插入一個文件
collection.insertOne(document);
}
插入多個文件,使用 MongoCollection 物件的 insertMany() 方法,該方法接收一個 資料型別為 Document 的 List 物件作為要插入的資料
//插入多個文件
@Test
public void insertManyTest(){
//獲取資料庫連線物件
MongoDatabase mongoDatabase = MongoDBUtil.getConnect();
//獲取集合
MongoCollection<Document> collection = mongoDatabase.getCollection("user");
//要插入的資料
List<Document> list = new ArrayList<>();
for(int i = 1; i <= 3; i++) {
Document document = new Document("name", "張三")
.append("sex", "男")
.append("age", 18);
list.add(document);
}
//插入多個文件
collection.insertMany(list);
}
4)刪除文件
刪除與篩選器匹配的單個文件,使用 MongoCollection 物件的 deleteOne() 方法,該方法接收一個數據型別為 Bson 的的物件作為過濾器篩選出需要刪除的文件。然後刪除第一個。為了便於建立過濾器物件,JDBC驅動程式提供了 Filters 類。
//刪除與篩選器匹配的單個文件
@Test
public void deleteOneTest(){
//獲取資料庫連線物件
MongoDatabase mongoDatabase = MongoDBUtil.getConnect();
//獲取集合
MongoCollection<Document> collection = mongoDatabase.getCollection("user");
//申明刪除條件
Bson filter = Filters.eq("age",18);
//刪除與篩選器匹配的單個文件
collection.deleteOne(filter);
}
刪除與篩選器匹配的所有文件,使用 MongoCollection 物件的 deleteMany() 方法,該方法接收一個數據型別為 Bson 的的物件作為過濾器篩選出需要刪除的文件。然後刪除所有篩選出的文件。
//刪除與篩選器匹配的所有文件
@Test
public void deleteManyTest(){
//獲取資料庫連線物件
MongoDatabase mongoDatabase = MongoDBUtil.getConnect();
//獲取集合
MongoCollection<Document> collection = mongoDatabase.getCollection("user");
//申明刪除條件
Bson filter = Filters.eq("age",18);
//刪除與篩選器匹配的所有文件
collection.deleteMany(filter);
}
5)修改文件
修改單個文件,使用 MongoCollection 物件的 updateOne() 方法,該方法接收兩個引數,第一個資料型別為 Bson 的過濾器篩選出需要修改的文件,第二個引數資料型別為 Bson 指定如何修改篩選出的文件。然後修改過濾器篩選出的第一個文件。
//修改單個文件
@Test
public void updateOneTest(){
//獲取資料庫連線物件
MongoDatabase mongoDatabase = MongoDBUtil.getConnect();
//獲取集合
MongoCollection<Document> collection = mongoDatabase.getCollection("user");
//修改過濾器
Bson filter = Filters.eq("name", "張三");
//指定修改的更新文件
Document document = new Document("$set", new Document("age", 100));
//修改單個文件
collection.updateOne(filter, document);
}
修改多個文件,使用 MongoCollection 物件的 updateMany() 方法,該方法接收兩個引數,第一個資料型別為 Bson 的過濾器篩選出需要修改的文件,第二個引數資料型別為 Bson 指定如何修改篩選出的文件。然後修改過濾器篩選出的所有文件。
//修改多個文件
@Test
public void updateManyTest(){
//獲取資料庫連線物件
MongoDatabase mongoDatabase = MongoDBUtil.getConnect();
//獲取集合
MongoCollection<Document> collection = mongoDatabase.getCollection("user");
//修改過濾器
Bson filter = Filters.eq("name", "張三");
//指定修改的更新文件
Document document = new Document("$set", new Document("age", 100));
//修改多個文件
collection.updateMany(filter, document);
}
6)查詢文件
使用 MongoCollection 物件的 find() 方法,該方法有多個過載方法,可以使用不帶引數的 find() 方法查詢集合中的所有文件,也可以通過傳遞一個 Bson 型別的 過濾器查詢符合條件的文件。這幾個過載方法均返回一個 FindIterable 型別的物件,可通過該物件遍歷出查詢到的所有文件。
查詢集合中的所有文件
//查詢集合中的所有文件
@Test
public void findTest(){
//獲取資料庫連線物件
MongoDatabase mongoDatabase = MongoDBUtil.getConnect();
//獲取集合
MongoCollection<Document> collection = mongoDatabase.getCollection("user");
//查詢集合中的所有文件
FindIterable findIterable = collection.find();
MongoCursor cursor = findIterable.iterator();
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
}
指定查詢過濾器查詢
//指定查詢過濾器查詢
@Test
public void FilterfindTest(){
//獲取資料庫連線物件
MongoDatabase mongoDatabase = MongoDBUtil.getConnect();
//獲取集合
MongoCollection<Document> collection = mongoDatabase.getCollection("user");
//指定查詢過濾器
Bson filter = Filters.eq("name", "張三");
//指定查詢過濾器查詢
FindIterable findIterable = collection.find(filter);
MongoCursor cursor = findIterable.iterator();
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
}
可通過 first() 方法取出查詢到的第一個文件
//取出查詢到的第一個文件
@Test
public void findTest(){
//獲取資料庫連線物件
MongoDatabase mongoDatabase = MongoDBUtil.getConnect();
//獲取集合
MongoCollection<Document> collection = mongoDatabase.getCollection("user");
//查詢集合中的所有文件
FindIterable findIterable = collection.find();
//取出查詢到的第一個文件
Document document = (Document) findIterable.first();
//列印輸出
System.out.println(document);
}
4、總結
到這裡,java對mongoDB的一些基本操作就介紹完了。實現的步驟為:新增驅動==>連線到服務==>連線到資料庫==>選擇集合==>對集合進行CRUD操作。