MongoDB BSON Guide – MongoDB BSON指南

最后修改: 2019年 4月 29日

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

1. Introduction

1.绪论

In this tutorial, we’ll be looking at BSON and how we can use it to interact with MongoDB.

在本教程中,我们将了解BSON以及如何使用它与MongoDB进行交互。

Now, an in-depth description of MongoDB and all of its capabilities is beyond the scope of this article. However, it’ll be useful to understand a few key concepts.

现在,对MongoDB及其所有功能的深入描述已经超出了本文的范围。然而,了解一些关键的概念会很有用。

MongoDB is a distributed, NoSQL document storage engine. Documents are stored as BSON data and grouped together into collections. Documents in a collection are analogous to rows in a relational database table.

MongoDB是一个分布式的、NoSQL文档存储引擎。文档被存储为BSON数据,并被分组为集合。集合中的文件类似于关系型数据库表中的行

For a more in-depth look, have a look at the introductory MongoDB article.

如需更深入的了解,请看MongoDB介绍性文章

2. What Is BSON?

2.什么是BSON

BSON stands for Binary JSON. It’s a protocol for binary serialization of JSON-like data.

BSON代表二进制JSON。它是一种用于对类似JSON的数据进行二进制序列化的协议。

JSON is a data exchange format that is popular in modern web services. It provides a flexible way to represent complex data structures.

JSON是一种数据交换格式,在现代网络服务中很流行。它提供了一种灵活的方式来表示复杂的数据结构。

BSON provides several advantages over using regular JSON:

与使用普通的JSON相比,BSON有几个优点。

  • Compact: In most cases, storing a BSON structure requires less space than its JSON equivalent
  • Data Types: BSON provides additional data types not found in regular JSON, such as Date and BinData

One of the main benefits of using BSON is that it’s easy to traverse. BSON documents contain additional metadata that allow for easy manipulation of the fields of a document, without having to read the entire document itself.

使用BSON的主要好处之一是它易于遍历。BSON文档包含额外的元数据,可以轻松操作文档的字段,而不必阅读整个文档本身。

3. The MongoDB Driver

3.MongoDB驱动程序

Now that we have a basic understanding of BSON and MongoDB, let’s look at how to use them together. We’ll focus on the main actions from the CRUD acronym (Create, Read, Update, Delete).

现在我们对BSON和MongoDB有了基本的了解,让我们看看如何将它们结合起来使用。我们将重点关注CRUD缩写中的主要操作(Create, Read, Update, Delete)。

MongoDB provides software drivers for most modern programming languages. The drivers are built on top of the BSON library, which means we’ll be working directly with the BSON API when building queries. For more information, see our guide to the MongoDB query language.

MongoDB 为大多数现代编程语言提供软件驱动程序这些驱动程序是建立在BSON库之上的,这意味着我们在构建查询时将直接使用BSON API。有关详细信息,请参阅我们的MongoDB 查询语言指南

In this section, we’ll look at using the driver to connect to a cluster, and using the BSON API to perform different types of queries. Note that the MongoDB driver provides a Filters class that can help us write more compact code. For this tutorial, however, we’ll focus solely on using the core BSON API.

在本节中,我们将探讨使用驱动程序连接到集群,以及使用BSON API来执行不同类型的查询。请注意,MongoDB 驱动程序提供了一个Filters,可以帮助我们编写更紧凑的代码。然而,在本教程中,我们将只关注使用核心的BSON API。

As an alternative to using the MongoDB driver and BSON directly, take a look at our Spring Data MongoDB guide.

作为直接使用 MongoDB 驱动程序和 BSON 的替代方案,请查看我们的 Spring Data MongoDB 指南

3.1. Connecting

3.1.连接

To get started, we first add the MongoDB driver as a dependency into our application:

为了开始工作,我们首先将MongoDB驱动程序作为一个依赖项添加到我们的应用程序中。

<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongodb-driver-sync</artifactId>
    <version>3.10.1</version>
</dependency>

Then we create a connection to a MongoDB database and collection:

然后我们创建一个与MongoDB数据库和集合的连接。

MongoClient mongoClient = MongoClients.create();
MongoDatabase database = mongoClient.getDatabase("myDB");
MongoCollection<Document> collection = database.getCollection("employees");

The remaining sections will look at creating queries using the collection reference.

剩下的章节将探讨如何使用collection引用创建查询。

3.2. Insert

3.2 插入

Let’s say we have the following JSON that we want to insert as a new document into an employees collection:

假设我们有以下JSON,我们想把它作为一个新的文档插入到employees集合中。

{
  "first_name" : "Joe",
  "last_name" : "Smith",
  "title" : "Java Developer",
  "years_of_service" : 3,
  "skills" : ["java","spring","mongodb"],
  "manager" : {
     "first_name" : "Sally",
     "last_name" : "Johanson"
  }
}

This example JSON shows the most common data types we would encounter with MongoDB documents: text, numeric, arrays, and embedded documents.

这个JSON例子显示了我们在MongoDB文档中会遇到的最常见的数据类型:文本、数字、数组和嵌入式文档。

To insert this using BSON, we’d use MongoDB’s Document API:

为了使用BSON插入这个,我们会使用MongoDB的Document API。

Document employee = new Document()
    .append("first_name", "Joe")
    .append("last_name", "Smith")
    .append("title", "Java Developer")
    .append("years_of_service", 3)
    .append("skills", Arrays.asList("java", "spring", "mongodb"))
    .append("manager", new Document()
                           .append("first_name", "Sally")
                           .append("last_name", "Johanson"));
collection.insertOne(employee);

The Document class is the primary API used in BSON. It extends the Java Map interface and contains several overloaded methods. This makes it easy to work with native types as well as common objects such as object IDs, dates, and lists.

Document类是BSON中使用的主要API。它扩展了Java的Map接口,并包含几个重载方法。这使得它很容易处理本地类型以及常见的对象,如对象ID、日期和列表。

3.3. Find

3.3. 查找

To find a document in MongoDB, we provide a search document that specifies which fields to query on. For example, to find all documents that have a last name of “Smith” we would use the following JSON document:

为了在MongoDB中找到一个文档,我们提供一个搜索文档,指定要查询哪些字段。例如,要找到所有姓氏为 “Smith “的文档,我们将使用以下JSON文档。

{  
  "last_name": "Smith"
}

Written in BSON this would be:

用BSON写的就是这个。

Document query = new Document("last_name", "Smith");
List results = new ArrayList<>();
collection.find(query).into(results);

“Find” queries can accept multiple fields and the default behavior is to use the logical and operator to combine them. This means only documents that match all fields will be returned.

“查找 “查询可以接受多个字段,默认行为是使用逻辑and操作符来组合它们。这意味着只有符合所有字段的文件才会被返回

To get around this, MongoDB provides the or query operator:

为了解决这个问题,MongoDB提供了or查询操作员。

{
  "$or": [
    { "first_name": "Joe" },
    { "last_name":"Smith" }
  ]
}

This will find all documents that have either first name “Joe” or last name “Smith”. To write this as BSON, we would use a nested Document just like the insert query above:

这将找到所有名字为 “Joe “或姓氏为 “Smith “的文档。要把这个写成BSON,我们将使用一个嵌套的Document,就像上面的插入查询一样。

Document query = 
  new Document("$or", Arrays.asList(
      new Document("last_name", "Smith"),
      new Document("first_name", "Joe")));
List results = new ArrayList<>();
collection.find(query).into(results);

3.4. Update

3.4.更新

Update queries are a little different in MongoDB because they require two documents:

更新查询在MongoDB中有些不同,因为它们需要两个文档

  1. The filter criteria to find one or more documents
  2. An update document specifying which fields to modify

For example, let’s say we want to add a “security” skill to every employee that already has a “spring” skill. The first document will find all employees with “spring” skills, and the second one will add a new “security” entry to their skills array.

例如,假设我们想给每个已经拥有 “spring “技能的雇员添加一个 “security “技能。第一个文件将找到所有拥有 “spring “技能的员工,第二个文件将在他们的技能阵列中添加一个新的 “security “条目。

In JSON, these two queries would look like:

在JSON中,这两个查询看起来像。

{
  "skills": { 
    $elemMatch:  { 
      "$eq": "spring"
    }
  }
}

{
  "$push": { 
    "skills": "security"
  }
}

And in BSON, they would be:

而在BSON,他们将是。

Document query = new Document(
  "skills",
  new Document(
    "$elemMatch",
    new Document("$eq", "spring")));
Document update = new Document(
  "$push",
  new Document("skills", "security"));
collection.updateMany(query, update);

3.5. Delete

3.5.删除

Delete queries in MongoDB use the same syntax as find queries. We simply provide a document that specifies one or more criteria to match.

MongoDB中的删除查询使用与查找查询相同的语法。我们只需提供一个文件,指定一个或多个要匹配的标准。

For example, let’s say we found a bug in our employee database and accidentally created employees a with a negative value for years of service. To find them all, we would use the following JSON:

例如,假设我们在员工数据库中发现了一个错误,不小心创建了一个服务年限为负值的员工。为了找到他们所有人,我们将使用以下JSON。

{
  "years_of_service" : { 
    "$lt" : 0
  }
}

The equivalent BSON document would be:

相当于BSON的文件将是。

Document query = new Document(
  "years_of_service", 
  new Document("$lt", 0));
collection.deleteMany(query);

4. Conclusion

4.总结

In this tutorial, we’ve seen a basic introduction to building MongoDB queries using the BSON library. Using only the BSON API, we implemented basic CRUD operations for a MongoDB collection.

在本教程中,我们已经看到了使用BSON库构建MongoDB查询的基本介绍。我们仅使用BSON API,就实现了对MongoDB集合的基本CRUD操作。

What we have not covered are more advanced topics such as projections, aggregations, geospatial queries, bulk operations, and more. All of these are possible using just the BSON library. The examples we’ve seen here form the building blocks we would use to implement these more advanced operations.

我们没有涉及的是更高级的主题,如投影、聚合、地理空间查询、批量操作等等。所有这些都可以通过BSON库来实现。我们在这里看到的例子构成了我们用来实现这些更高级操作的基石。

As always, you can find the code examples above in our GitHub repo.

一如既往,您可以在我们的GitHub repo中找到上述代码示例。