Java如何连接到MongoDB数据库?

在上一篇文章中,您已经了解了我们如何安装MongoDB数据库服务器,并尝试使用MongoDB Shell来操纵数据库中的集合。还向您介绍了如何获取和设置MongoDB Java驱动程序,我们可以使用该驱动程序通过Java程序来操作MongoDB数据库。

从这篇文章开始,我们将开始探索更多有关如何使用MongoDB Java驱动程序与MongoDB一起使用的功能。您将看到我们如何连接到数据库,如何使用Java驱动程序执行CRUD操作(创建,读取,更新和删除)。但是首先让我们看看如何在MongoDB中创建与数据库的连接。

这是我们的第一个代码段,它向您展示如何引导MongoDB来打开与数据库的连接。

package org.nhooo.example.mongodb;

import com.mongodb.*;

import java.net.UnknownHostException;
import java.util.Random;

public class MongoDBConnect {
    public static void main(String[] args) {
        try {
            MongoClient client =
                new MongoClient(new ServerAddress("localhost", 27017));

            DB database = client.getDB("school");
            DBCollection students = database.getCollection("students");
            students.remove(new BasicDBObject());

            String[] types = {"Homework", "Quiz", "Essay"};
            for (int i = 1; i <= 10; i++) {
                for (int j = 0; j < 3; j++) {
                    students.insert(new BasicDBObject("student_id", i)
                        .append("type", types[j])
                        .append("score", new Random().nextInt(100)));
                }
            }

            try (DBCursor cursor = students.find()) {
                while (cursor.hasNext()) {
                    System.out.println(cursor.next());
                }
            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }
}

您可以从上面的代码中看到。首先,我们通过创建的实例来引导MongoDB MongoClient。在这里,我们传递一个,ServerAddress以定义有关主机名和端口号的信息的MongoDB数据库的地址。如果您仅创建一个MongoClient不带任何参数的实例,它将使用默认地址(例如localhost主机)和27017默认端口号。创建的实例MongoClient可以产生UnknownHostException,因此我们需要将其放入try-catch语句中。

try {
    MongoClient client =
        new MongoClient(new ServerAddress("localhost", 27017));
} catch (UnknownHostException e) {
    e.printStackTrace();
}

初始化后,MongoClient我们可以通过调用getDB()方法并将数据库名称作为参数来连接到数据库。在上面的示例中,我们连接到school数据库,MongoDB中的数据库由包中的DB类表示com.mongodb。连接到数据库后的下一行,您可以看到我们正在students从该数据库获取集合。仅出于本示例的目的,我们然后students使用类的remove()方法清空集合DBCollection。

DB database = client.getDB("school");
DBCollection students = database.getCollection("students");
students.remove(new BasicDBObject());

在接下来的几行中,直到代码片段的结尾,您可以看到我们将一些随机数据填充到students集合中。我们调用DBCollection.insert()将文档插入students集合中的方法。最后,我们students使用find()方法从集合中读取插入的文档,并逐一迭代返回的游标,直到所有文档打印在控制台上。您还可以看到,由于该代码DBCursor已经实现了Java 7 AutoCloseable接口,因此在此代码中使用了try-with-resource语法。

String[] types = {"Homework", "Quiz", "Essay"};
for (int i = 1; i <= 10; i++) {
    for (int j = 0; j < 3; j++) {
        students.insert(new BasicDBObject("student_id", i)
            .append("type", types[j])
            .append("score", new Random().nextInt(100)));
    }
}

try (DBCursor cursor = students.find()) {
    while (cursor.hasNext()) {
        System.out.println(cursor.next());
    }
}

这是上面我们的代码产生的结果的样本。

{ "_id" : { "$oid" : "53f47814f524c5037606f2b4"} , "student_id" : 1 , "type" : "Homework" , "score" : 86}
{ "_id" : { "$oid" : "53f47814f524c5037606f2b5"} , "student_id" : 1 , "type" : "Quiz" , "score" : 14}
{ "_id" : { "$oid" : "53f47814f524c5037606f2b6"} , "student_id" : 1 , "type" : "Essay" , "score" : 35}
{ "_id" : { "$oid" : "53f47814f524c5037606f2b7"} , "student_id" : 2 , "type" : "Homework" , "score" : 12}
{ "_id" : { "$oid" : "53f47814f524c5037606f2b8"} , "student_id" : 2 , "type" : "Quiz" , "score" : 96}
{ "_id" : { "$oid" : "53f47814f524c5037606f2b9"} , "student_id" : 2 , "type" : "Essay" , "score" : 51}
{ "_id" : { "$oid" : "53f47814f524c5037606f2ba"} , "student_id" : 3 , "type" : "Homework" , "score" : 54}
{ "_id" : { "$oid" : "53f47814f524c5037606f2bb"} , "student_id" : 3 , "type" : "Quiz" , "score" : 50}
{ "_id" : { "$oid" : "53f47814f524c5037606f2bc"} , "student_id" : 3 , "type" : "Essay" , "score" : 38}
{ "_id" : { "$oid" : "53f47814f524c5037606f2bd"} , "student_id" : 4 , "type" : "Homework" , "score" : 69}