Java連接MongoDB操作

在本章中,我們將學習如何設置和使用MongoDB JDBC驅動程序。

安裝 MongoDB JDBC驅動程序

要在Java程序中使用MongoDB之前,需要確保在機器上設置了MongoDB JDBC驅動程序和Java。 可以在機器上檢查Java環境可通過:Java教程。 現在,我們來看一下如何設置MongoDB JDBC驅動。

連接到數據庫

要連接數據庫,需要指定數據庫名稱,如果數據庫不存在,那麼MongoDB會自動創建它。
使用 Eclipse 創建一個 Maven 工程 - MongoDBJDBC ,其目錄結果如下所示 -

Java連接MongoDB操作

有關 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", "http://www.yiibai.com/mongodb/");

            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" : "http://www.yiibai.com", "tags" : ["mongodb", "database", "NoSQL"], "likes" : 100.0 }
{ "_id" : 100.0, "title" : "MongoDB Overview", "description" : "MongoDB is no sql database", "by" : "yiibai tutorials", "url" : "http://www.yiibai.com", "tags" : ["mongodb", "database", "NoSQL"], "likes" : 100.0 }
{ "_id" : 1999, "title" : "MongoDB Insert Demo", "description" : "database", "likes" : 30, "by" : "yiibai point", "url" : "http://www.yiibai.com/mongodb/" }
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", "http://www.yiibai.com/mongodb/");

            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" : "http://www.yiibai.com/mongodb/" }
{ "_id" : 9999, "title" : "MongoDB Insert Demo", "description" : "database", "likes" : 30, "by" : "yiibai point", "url" : "http://www.yiibai.com/mongodb/" }
{ "_id" : 1999, "title" : "更新了標題2", "description" : "database", "likes" : 30, "by" : "yiibai point", "url" : "http://www.yiibai.com/mongodb/" }
{ "_id" : 9999, "title" : "更新了標題2", "description" : "database", "likes" : 30, "by" : "yiibai point", "url" : "http://www.yiibai.com/mongodb/" }

刪除文檔

要從集合中刪除第一個文檔,需要首先使用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", "http://www.yiibai.com/mongodb/");

            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" : "http://www.yiibai.com/mongodb/" }
{ "_id" : 9999, "title" : "更新了標題2", "description" : "database", "likes" : 30, "by" : "yiibai point", "url" : "http://www.yiibai.com/mongodb/" }
After Delete Document:
{ "_id" : 1999, "title" : "更新了標題2", "description" : "database", "likes" : 30, "by" : "yiibai point", "url" : "http://www.yiibai.com/mongodb/" }