Java Mongodb 简明教程

Java & MongoDB - Overview

MongoDB 开发者团队提供了适用于 Java 的 MongoDB 驱动程序,并为此准备了各种资源。

MongoDB developer team has provided MongoDB Driver for Java and have various resources available for it.

使用 Java 连接到 MongoDB 的第一步是,将 mongodb 驱动程序放入 Java 类路径,然后使用 mongodb API 连接到数据库。

First step in connecting to MongoDB using Java is to have mongodb driver in the java classpath and then use mongodb API to connect to the database.

Connecting to MongoDB database

假设已在本机安装 MongoDB,并且使用的是默认端口,则可以使用以下语法连接到 MongoDB 数据库。

Suppose, MongoDB is installed locally and using default port then following syntax connects to MongoDB database.

MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");

因为 MongoClient 采用了各种默认设置,因此也可以按照以下方式使用它。

As MongoClient assumes various default, it can be used using the following way as well.

MongoClient mongoClient = MongoClients.create();

Creating/Connecting to Database

实例化 mongoClient 后,可以使用其 getDatabase() 方法获取与数据库的连接。

Once mongoClient is instantiated, its getDatabase() method can be used to get connection to a database.

MongoDatabase database = mongoClient.getDatabase("myDb");

如果数据库不存在,则上述命令会创建数据库。

In case database is not present then above command will create the same.

后续章节中,我们将使用 Java 演示基于 MongoDB 的各种操作。

In subsequent chapters, we’ll see the various operations on MongoDB using Java.