在本章中,我們將學習如何設定和使用MongoDB JDBC驅動程式。
要在Java程式中使用MongoDB之前,需要確保在機器上設定了MongoDB JDBC驅動程式和Java。 可以在機器上檢查Java環境可通過:Java教學。 現在,我們來看一下如何設定MongoDB JDBC驅動。
要連線資料庫,需要指定資料庫名稱,如果資料庫不存在,那麼MongoDB會自動建立它。
使用 Eclipse 建立一個 Maven 工程 - MongoDBJDBC ,其目錄結果如下所示 -
有關 pom.xml
檔案的內容如下 -
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.yiibai</groupId>
<artifactId>MongoDBJDBC</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>MongoDBJDBC</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver</artifactId>
<version>3.4.2</version>
</dependency>
</dependencies>
<build>
<defaultGoal>compile</defaultGoal>
</build>
</project>
以下是連線到資料庫的程式碼片段 -
package com.yiibai.MongoDBJDBC;
/**
* Hello world!
*
*/
import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;
public class App {
public static void main(String args[]) {
try {
// To connect to mongodb server
MongoClient mongoClient = new MongoClient("localhost", 27017);
// Now connect to your databases
MongoDatabase mgdb = mongoClient.getDatabase("mycol");
System.out.println("Connect to database successfully!");
System.out.println("MongoDatabase inof is : "+mgdb.getName());
// If MongoDB in secure mode, authentication is required.
// boolean auth = db.authenticate(myUserName, myPassword);
// System.out.println("Authentication: "+auth);
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
}
}
預設認證機制
String user; // the user name
String database; // the name of the database in which the user is defined
char[] password; // the password as a character array
// ...
MongoCredential credential = MongoCredential.createCredential(user, database, password);
MongoClient mongoClient = new MongoClient(new ServerAddress("host1", 27017),
Arrays.asList(credential));
或者使用連線字串而不明確指定認證機制:
MongoClientURI uri = new MongoClientURI("mongodb://user1:pwd1@host1/?authSource=db1");
MongoClient mongoClient = new MongoClient(uri);
執行上面程式碼,得到以下結果 -
com.mongodb.diagnostics.logging.JULLogger log
資訊: Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
Connect to database successfully!
MongoDatabase inof is : mycol
要建立集合,可使用 com.mongodb.DB
類的 createCollection()
方法。
以下是建立集合的程式碼片段 -
package com.yiibai.MongoDBJDBC;
import org.bson.Document;
import com.mongodb.DBCollection;
import com.mongodb.client.model.CreateCollectionOptions;
/**
* Hello world!
*
*/
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
public class CreateCollection {
public static void main(String args[]) {
try {
// To connect to mongodb server
MongoClient mongoClient = new MongoClient("localhost", 27017);
// Now connect to your databases
MongoDatabase database = mongoClient.getDatabase("test");
//database.createCollection("NewCollection",new CreateCollectionOptions().capped(true).sizeInBytes(0x100000));
MongoCollection<Document> coll = database.getCollection("myTestCollection");
System.out.println("Collection created successfully");
System.out.println("當前資料庫中的所有集合是:");
for (String name : database.listCollectionNames()) {
System.out.println(name);
}
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
}
}
執行上面程式碼,得到以下結果 -
Collection created successfully
當前資料庫中的所有集合是:
mycol
inventory
post
mycollection
newcollection
要將文件插入到MongoDB中,使用com.mongodb.DBCollection
類的insertOne()
方法。
以下是插入文件的程式碼片段 -
package com.yiibai.MongoDBJDBC;
import java.util.Arrays;
import org.bson.Document;
import com.mongodb.BasicDBObject;
import com.mongodb.Block;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
/**
* Hello world!
*
*/
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.CreateCollectionOptions;
public class InsertDocument {
public static void main(String args[]) {
try {
// To connect to mongodb server
MongoClient mongoClient = new MongoClient("localhost", 27017);
// Now connect to your databases
MongoDatabase database = mongoClient.getDatabase("test");
// database.createCollection("NewCollection", new
// CreateCollectionOptions().capped(true).sizeInBytes(0x100000));
System.out.println("Collection created successfully");
System.out.println("當前資料庫中的所有集合是:");
for (String name : database.listCollectionNames()) {
System.out.println(name);
}
MongoCollection coll = database.getCollection("mycol");
System.out.println("Collection mycol selected successfully");
MongoCollection<Document> collection = database.getCollection("mycol");
Document document = new Document("_id", 1999).append("title", "MongoDB Insert Demo")
.append("description","database")
.append("likes", 30)
.append("by", "yiibai point")
.append("url", "/18/141/4072.html");
collection.insertOne(document);
collection.find().forEach(printBlock);
System.out.println("Document inserted successfully");
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
}
static Block<Document> printBlock = new Block<Document>() {
public void apply(final Document document) {
System.out.println(document.toJson());
}
};
}
執行上面程式碼,得到以下結果 -
NewCollection
mycol
inventory
post
Collection
mycollection
newcollection
Collection mycol selected successfully
{ "_id" : 123.0, "title" : "MongoDB Overview", "description" : "MongoDB is no sql database", "by" : "yiibai tutorials", "url" : "https://www.tw511.com", "tags" : ["mongodb", "database", "NoSQL"], "likes" : 100.0 }
{ "_id" : 100.0, "title" : "MongoDB Overview", "description" : "MongoDB is no sql database", "by" : "yiibai tutorials", "url" : "https://www.tw511.com", "tags" : ["mongodb", "database", "NoSQL"], "likes" : 100.0 }
{ "_id" : 1999, "title" : "MongoDB Insert Demo", "description" : "database", "likes" : 30, "by" : "yiibai point", "url" : "/18/141/4072.html" }
Document inserted successfully
如何插入多行?
Document doc1 = new Document("name", "Amarcord Pizzeria")
.append("contact", new Document("phone", "264-555-0193")
.append("email", "[email protected]")
.append("location",Arrays.asList(-73.88502, 40.749556)))
.append("stars", 2)
.append("categories", Arrays.asList("Pizzeria", "Italian", "Pasta"));
Document doc2 = new Document("name", "Blue Coffee Bar")
.append("contact", new Document("phone", "604-555-0102")
.append("email", "[email protected]")
.append("location",Arrays.asList(-73.97902, 40.8479556)))
.append("stars", 5)
.append("categories", Arrays.asList("Coffee", "Pastries"));
List<Document> documents = new ArrayList<Document>();
documents.add(doc1);
documents.add(doc2);
collection.insertMany(documents);
要從集合更新文件,使用com.mongodb.DBCollection
類的update()
和updateMany()
方法。以下是選擇第一個文件的程式碼片段 -
package com.yiibai.MongoDBJDBC;
import org.bson.Document;
import com.mongodb.Block;
/**
* Hello world!
*
*/
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoCollection;
import org.bson.Document;
import com.mongodb.client.MongoCursor;
import static com.mongodb.client.model.Filters.*;
import com.mongodb.client.result.DeleteResult;
import static com.mongodb.client.model.Updates.*;
import com.mongodb.client.result.UpdateResult;
import java.util.ArrayList;
import java.util.List;
public class App {
public static void main(String args[]) {
try {
// To connect to mongodb server
MongoClient mongoClient = new MongoClient("127.0.0.1", 27017);
// Now connect to your databases
MongoDatabase database = mongoClient.getDatabase("mycol");
System.out.println("Connect to database successfully!");
System.out.println("MongoDatabase inof is : "+database.getName());
MongoCollection<Document> collection = database.getCollection("mycol");
//collection.updateOne(eq("_id", 1999),new Document("$set", new Document("title", "更新了標題2")));
Document document = new Document("_id", 9999).append("title", "MongoDB Insert Demo")
.append("description","database")
.append("likes", 30)
.append("by", "yiibai point")
.append("url", "/18/141/4072.html");
collection.insertOne(document);
collection.find().forEach(printBlock);
collection.updateOne(eq("_id", 9999),new Document("$set", new Document("title", "更新了標題2")));
collection.find().forEach(printBlock);
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
}
static Block<Document> printBlock = new Block<Document>() {
public void apply(final Document document) {
System.out.println(document.toJson());
}
};
}
執行上面程式碼,得到以下結果 -
{ "_id" : 1999, "title" : "更新了標題2", "description" : "database", "likes" : 30, "by" : "yiibai point", "url" : "/18/141/4072.html" }
{ "_id" : 9999, "title" : "MongoDB Insert Demo", "description" : "database", "likes" : 30, "by" : "yiibai point", "url" : "/18/141/4072.html" }
{ "_id" : 1999, "title" : "更新了標題2", "description" : "database", "likes" : 30, "by" : "yiibai point", "url" : "/18/141/4072.html" }
{ "_id" : 9999, "title" : "更新了標題2", "description" : "database", "likes" : 30, "by" : "yiibai point", "url" : "/18/141/4072.html" }
要從集合中刪除第一個文件,需要首先使用findOne()
方法選擇文件,然後使用com.mongodb.DBCollection
類的remove()
方法。
以下是刪除第一個文件的程式碼片段 -
package com.yiibai.MongoDBJDBC;
import org.bson.Document;
import com.mongodb.Block;
/**
* Hello world!
*
*/
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoCollection;
import org.bson.Document;
import com.mongodb.client.MongoCursor;
import static com.mongodb.client.model.Filters.*;
import com.mongodb.client.result.DeleteResult;
import static com.mongodb.client.model.Updates.*;
import com.mongodb.client.result.UpdateResult;
import java.util.ArrayList;
import java.util.List;
public class App {
public static void main(String args[]) {
try {
// To connect to mongodb server
MongoClient mongoClient = new MongoClient("127.0.0.1", 27017);
// Now connect to your databases
MongoDatabase database = mongoClient.getDatabase("mycol");
System.out.println("Connect to database successfully!");
System.out.println("MongoDatabase inof is : "+database.getName());
// 更新文件
MongoCollection<Document> collection = database.getCollection("mycol");
/**
Document document = new Document("_id", 9999).append("title", "MongoDB Insert Demo")
.append("description","database")
.append("likes", 30)
.append("by", "yiibai point")
.append("url", "/18/141/4072.html");
collection.insertOne(document);
//collection.find().forEach(printBlock);
//collection.updateOne(eq("_id", 9999),new Document("$set", new Document("title", "更新了標題2")));
*/
collection.find().forEach(printBlock);
// 刪除文件
collection.deleteOne(eq("_id", 9999));
System.out.println("After Delete Document:");
collection.find().forEach(printBlock);
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
}
static Block<Document> printBlock = new Block<Document>() {
public void apply(final Document document) {
System.out.println(document.toJson());
}
};
}
執行上面程式碼,得到以下結果 -
{ "_id" : 1999, "title" : "更新了標題2", "description" : "database", "likes" : 30, "by" : "yiibai point", "url" : "/18/141/4072.html" }
{ "_id" : 9999, "title" : "更新了標題2", "description" : "database", "likes" : 30, "by" : "yiibai point", "url" : "/18/141/4072.html" }
After Delete Document:
{ "_id" : 1999, "title" : "更新了標題2", "description" : "database", "likes" : 30, "by" : "yiibai point", "url" : "/18/141/4072.html" }