MongoDB最簡單的入門教程之三 使用Java代碼往MongoDB裏插入數據

前兩篇教程咱們介紹瞭如何搭建MongoDB的本地環境:java

MongoDB最簡單的入門教程之一 環境搭建node

以及如何用nodejs讀取MongoDB裏的記錄:git

MongoDB最簡單的入門教程之二 使用nodejs訪問MongoDBgithub

這篇教程咱們會介紹如何使用Java代碼來鏈接MongoDB。mongodb

若是您是基於Maven進行依賴管理的Java項目,只須要在您的pom.xml里加入下面的依賴定義,數據庫

<dependency>

<groupId>org.mongodb</groupId>

<artifactId>mongodb-driver</artifactId>

<version>3.6.4</version>

</dependency>

而後使用命令行mvn clean install後,您的本地maven倉庫裏會多出三個和用Java鏈接MongoDB相關的庫:maven

  • bsonspa

  • mongodb-driver命令行

  • mongodb-driver-corecode

固然也能夠手動逐一下載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數據庫裏增長記錄。

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);
}

執行Java應用,發現經過insert方法加到數據庫的記錄也能被順利讀出來。

MongoDB最簡單的入門教程之三 使用Java代碼往MongoDB裏插入數據

MongoDB最簡單的入門教程之三 使用Java代碼往MongoDB裏插入數據

要獲取更多Jerry的原創技術文章,請關注公衆號"汪子熙"或者掃描下面二維碼:

相關文章
相關標籤/搜索