A Guide to MongoDB with Java – 使用Java的MongoDB指南

最后修改: 2017年 1月 11日

中文/混合/英文(键盘快捷键:t)

 

1. Overview

1.概述

In this article, we’ll have a look at integrating MongoDB, a very popular NoSQL open source database with a standalone Java client.

在本文中,我们将看看如何将MongoDB(一个非常流行的NoSQL开源数据库)与独立的Java客户端进行集成。

MongoDB is written in C++ and has quite a number of solid features such as map-reduce, auto-sharding, replication, high availability etc.

MongoDB是用C++编写的,有相当多的可靠功能,如地图还原、自动分片、复制、高可用性等。

2. MongoDB

2.MongoDB

Let’s start with a few key points about MongoDB itself:

让我们从关于MongoDB本身的几个关键点开始。

  • stores data in JSON-like documents that can have various structures
  • uses dynamic schemas, which means that we can create records without predefining anything
  • the structure of a record can be changed simply by adding new fields or deleting existing ones

The above-mentioned data model gives us the ability to represent hierarchical relationships, to store arrays and other more complex structures easily.

上述数据模型使我们有能力表示层次关系,轻松存储数组和其他更复杂的结构。

3. Terminologies

3.术语

Understanding concepts in MongoDB becomes easier if we can compare them to relational database structures.

如果我们能将MongoDB中的概念与关系型数据库结构进行比较,理解这些概念就会变得更容易。

Let’s see the analogies between Mongo and a traditional MySQL system:

让我们看看Mongo和传统MySQL系统之间的类比。

  • Table in MySQL becomes a Collection in Mongo
  • Row becomes a Document
  • Column becomes a Field
  • Joins are defined as linking and embedded documents

This is a simplistic way to look at the MongoDB core concepts of course, but nevertheless useful.

当然,这是看待MongoDB核心概念的一种简单化的方式,但还是很有用。

Now, let’s dive into implementation to understand this powerful database.

现在,让我们深入实施,了解这个强大的数据库。

4. Maven Dependencies

4.Maven的依赖性

We need to start by defining the dependency of a Java Driver for MongoDB:

我们需要从定义MongoDB的Java驱动的依赖性开始。

<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongo-java-driver</artifactId>
    <version>3.4.1</version>
</dependency>

To check if any new version of the library has been released – track the releases here.

要检查库的任何新版本是否已经发布–跟踪这里的发布情况

5. Using MongoDB

5.使用MongoDB

Now, let’s start implementing Mongo queries with Java. We will follow with the basic CRUD operations as they are the best to start with.

现在,让我们开始用Java实现Mongo查询。我们将遵循基本的CRUD操作,因为它们是最好的开始。

5.1. Make a Connection With MongoClient

5.1.与MongoClient建立连接。

First, let’s make a connection to a MongoDB server. With version >= 2.10.0, we’ll use the MongoClient:

首先,让我们建立一个与MongoDB服务器的连接。如果版本>=2.10.0,我们将使用MongoClient

MongoClient mongoClient = new MongoClient("localhost", 27017);

And for older versions use Mongo class:

而对于旧版本则使用Mongoclass。

Mongo mongo = new Mongo("localhost", 27017);

5.2. Connecting to a Database

5.2.连接到一个数据库

Now, let’s connect to our database. It is interesting to note that we don’t need to create one. When Mongo sees that database doesn’t exist, it will create it for us:

现在,让我们连接到我们的数据库。值得注意的是,我们不需要创建一个。当Mongo看到数据库不存在时,它将为我们创建它。

DB database = mongoClient.getDB("myMongoDb");

Sometimes, by default, MongoDB runs in authenticated mode. In that case, we need to authenticate while connecting to a database.

有时,在默认情况下,MongoDB是以认证模式运行的。在这种情况下,我们需要在连接到数据库时进行身份验证。

We can do it as presented below:

我们可以按照下面的方式进行。

MongoClient mongoClient = new MongoClient();
DB database = mongoClient.getDB("myMongoDb");
boolean auth = database.authenticate("username", "pwd".toCharArray());

5.3. Show Existing Databases

5.3.显示现有的数据库

Let’s display all existing databases. When we want to use the command line, the syntax to show databases is similar to MySQL:

让我们来显示所有现有的数据库。当我们想使用命令行时,显示数据库的语法与MySQL相似。

show databases;

In Java, we display databases using snippet below:

在Java中,我们使用下面的片段显示数据库。

mongoClient.getDatabaseNames().forEach(System.out::println);

The output will be:

输出结果将是。

local      0.000GB
myMongoDb  0.000GB

Above, local is the default Mongo database.

以上,local是默认的Mongo数据库。

5.4. Create a Collection

5.4.创建一个集合

Let’s start by creating a Collection (table equivalent for MongoDB) for our database. Once we have connected to our database, we can make a Collection as:

让我们首先为我们的数据库创建一个Collection(相当于MongoDB的表)。一旦我们连接到我们的数据库,我们就可以创建一个Collection作为。

database.createCollection("customers", null);

Now, let’s display all existing collections for current database:

现在,让我们显示当前数据库的所有现有集合。

database.getCollectionNames().forEach(System.out::println);

The output will be:

输出结果将是。

customers

5.5. Save – Insert

5.5.保存-插入

The save operation has save-or-update semantics: if an id is present, it performs an update, if not – it does an insert.

保存操作具有保存或更新的语义:如果id存在,它执行更新,如果没有–它执行插入

When we save a new customer:

当我们保存一个新客户。

DBCollection collection = database.getCollection("customers");
BasicDBObject document = new BasicDBObject();
document.put("name", "Shubham");
document.put("company", "Baeldung");
collection.insert(document);

The entity will be inserted into a database:

该实体将被插入到数据库中。

{
    "_id" : ObjectId("33a52bb7830b8c9b233b4fe6"),
    "name" : "Shubham",
    "company" : "Baeldung"
}

Next, we’ll look at the same operation – save – with update semantics.

接下来,我们来看看同样的操作–save–与update语义。

5.6. Save – Update

5.6.保存 – 更新

Let’s now look at save with update semantics, operating on an existing customer:

现在让我们看看带有update语义的save,对一个现有客户进行操作。

{
    "_id" : ObjectId("33a52bb7830b8c9b233b4fe6"),
    "name" : "Shubham",
    "company" : "Baeldung"
}

Now, when we save the existing customer – we will update it:

现在,当我们保存现有客户时–我们将更新它。

BasicDBObject query = new BasicDBObject();
query.put("name", "Shubham");

BasicDBObject newDocument = new BasicDBObject();
newDocument.put("name", "John");

BasicDBObject updateObject = new BasicDBObject();
updateObject.put("$set", newDocument);

collection.update(query, updateObject);

The database will look like this:

该数据库将看起来像这样。

{
    "_id" : ObjectId("33a52bb7830b8c9b233b4fe6"),
    "name" : "John",
    "company" : "Baeldung"
}

As you can see, in this particular example, save uses the semantics of update, because we use object with given _id.

正如你所看到的,在这个特殊的例子中,save使用了update的语义,因为我们使用了具有给定_id的对象。

5.7. Read a Document From a Collection

5.7.从一个集合中读取文件

Let’s search for a Document in a Collection by making a query:

让我们通过查询在Collection中搜索一个Document

BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("name", "John");
DBCursor cursor = collection.find(searchQuery);

while (cursor.hasNext()) {
    System.out.println(cursor.next());
}

It will show the only Document we have by now in our Collection:

它将显示我们现在在Collection中的唯一Document

[
    {
      "_id" : ObjectId("33a52bb7830b8c9b233b4fe6"),
      "name" : "John",
      "company" : "Baeldung"
    }
]

5.8. Delete a Document

5.8.删除一个文件

Let’s move forward to our last CRUD operation, deletion:

让我们前进到我们的最后一个CRUD操作,删除。

BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("name", "John");

collection.remove(searchQuery);

With above command executed, our only Document will be removed from the Collection.

随着上述命令的执行,我们唯一的Document将从Collection中被删除。

6. Conclusion

6.结论

This article was a quick introduction to using MongoDB from Java.

这篇文章是对从Java使用MongoDB的快速介绍。

The implementation of all these examples and code snippets can be found over on GitHub – this is a Maven based project, so it should be easy to import and run as it is.

所有这些例子和代码片段的实现都可以在GitHub上找到–这是一个基于Maven的项目,所以应该很容易导入并按原样运行。