前兩篇教程我們介紹了如何搭建MongoDB的本地環(huán)境:
MongoDB最簡單的入門教程之一 環(huán)境搭建
以及如何用nodejs讀取MongoDB里的記錄:
MongoDB最簡單的入門教程之二 使用nodejs訪問MongoDB
這篇教程我們會介紹如何使用Java代碼來連接MongoDB。
如果您是基于Maven進(jìn)行依賴管理的Java項目,只需要在您的pom.xml里加入下面的依賴定義,
<dependency><groupId>org.mongodb</groupId><artifactId>mongodb-driver</artifactId><version>3.6.4</version></dependency>
然后使用命令行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<Document> collection) { Document document = new Document("name", "dog"); List<Document> documents = new ArrayList<Document>(); 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<Document> collection = mongoDatabase .getCollection("person"); // insert(collection);FindIterable<Document> findIterable = collection.find(); MongoCursor<Document> 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(); } }}
和教程二相比,上述代碼的insert方法里還展示了如何用Java代碼給MongoDB數(shù)據(jù)庫里增加記錄。
private static void insert(MongoCollection<Document> collection) { Document document = new Document("name", "dog"); List<Document> documents = new ArrayList<Document>(); documents.add(document); collection.insertMany(documents);}
執(zhí)行Java應(yīng)用,發(fā)現(xiàn)通過insert方法加到數(shù)據(jù)庫的記錄也能被順利讀出來。
MongoDB最簡單的入門教程之三 使用Java代碼往MongoDB里插入數(shù)據(jù)
MongoDB最簡單的入門教程之三 使用Java代碼往MongoDB里插入數(shù)據(jù)
要獲取更多Jerry的原創(chuàng)技術(shù)文章,請關(guān)注公眾號"汪子熙"。