28Java连接MongoDB操作


在本章中,我们将学习如何设置和使用MongoDB JDBC驱动程序。

安装 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>
XML

以下是连接到数据库的代码片段 –

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

默认认证机制

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

或者使用连接字符串而不明确指定认证机制:

MongoClientURI uri = new MongoClientURI("mongodb://user1:pwd1@host1/?authSource=db1");
MongoClient mongoClient = new MongoClient(uri);
Java

执行上面代码,得到以下结果 –

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
Shell

创建和列出集合

要创建集合,可使用 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());
        }
    }
}
Java

执行上面代码,得到以下结果 –

Collection created successfully
当前数据库中的所有集合是:
mycol
inventory
post
mycollection
newcollection
Shell

插入文档

要将文档插入到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());
        }
    };
}
Shell

执行上面代码,得到以下结果 –

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
Shell

如何插入多行?

Document doc1 = new Document("name", "Amarcord Pizzeria")
               .append("contact", new Document("phone", "264-555-0193")
                                       .append("email", "amarcord.pizzeria@example.net")
                                       .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", "bluecoffeebar@example.com")
                                       .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);
Java

更新文档

要从集合更新文档,使用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());
        }
    };
}
Java

执行上面代码,得到以下结果 –

{ "_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/" }
Shell

删除文档

要从集合中删除第一个文档,需要首先使用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());
        }
    };
}
Java

执行上面代码,得到以下结果 –

{ "_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/" }
Shell

 关注右侧公众号,随时随地查看教程 MongoDB教程目录 
转载自:https://www.yiibai.com/mongodb/mongodb_java.html

You may also like...

退出移动版