MongoDB 基础系列二:数据结构

前言

此篇博文是 Mongdb 基础系列之一;主要介绍 MongoDB 的数据结构;

本文为作者的原创作品,转载需注明出处;

简介

Mongodb 的数据结构主要由三部分构成,Database、Collection 以及 Document;Document 就是 Mongodb 中的一条记录;Collection 是由多个相同类型的 Documents 所组成;一个 Database 就是由多个不同类型的 Collections 所组成;下面,我们分别来看一看什么是 DatabaseCollection 以及 Document

Document

Mongodb 中的一条记录就是一个 Document,这个可以类比关系型数据库中的 Row;一个 Document 是一个 BSON object,BSON 是 JSON 的二进制表达方式,不过支持更多的数据类型;来看一个 Document 的例子,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
{
_id: ObjectId(7df78ad8902c)
title: 'MongoDB Overview',
description: 'MongoDB is no sql database',
by: 'tutorials point',
url: 'http://www.tutorialspoint.com',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 100,
comments: [
{
user:'user1',
message: 'My first comment',
dateCreated: new Date(2011,1,20,2,15),
like: 0
},
{
user:'user2',
message: 'My second comments',
dateCreated: new Date(2011,1,25,7,45),
like: 5
}
]
}

上述是某篇博文的记录,通过使用 Mongodb 的 Document 来作为一条记录而存储;可以看到,一个 Document 是由多个 key-value 构成,而,value 可以是数组或者是 Document,又或者是由多个 Documents 所组成的数组;这样定义 Document 的数据结构有三个优点,

  • Documents (i.e. objects) correspond to native data types in many programming languages.
  • Embedded documents and arrays reduce need for expensive joins.
  • Dynamic schema supports fluent polymorphism.

上述内容摘录自官文;头两条非常好理解,不太好理解的是第三点,Dynamic schema?什么是 Dynamic Schema,它又表达了什么意义?看 tutorialspoint 教程的一段描述,

Dynamic schema means that documents in the same collection do not need to have the same set of fields or structure, and common fields in a collection’s documents may hold different types of data.

Dynamic Schema的意思就是说,在同一个 Collection 当中的 Documents 之间不必具有相同的 field ( 就是 key ) 和结构,即便是相同的 field,也可以是不同类型的值;这个有点出乎我的意料了,关系型数据库中,一个 table 中的不同记录必须拥有相同的字段名以及字段类型,便于 join 和查询,可是,如果同一个 Collection 当中的不同的 Documents 的字段名和字段类型都不相同,又该如何进行批量查询和输出?Mongodb 为什么会这样来设计它的数据结构?这个有待笔者在后续学习当中去找到答案;

Collection

Collection 就是由一组 Documents 所构成的集合;它就等价于关系型数据库中的 table;正如 Document 中所阐述的那样,同一个 Collection 中的不同 Documents 之间的数据结构可以不同,既是可以拥有不同的字段名和字段类型;所以,Collection 中所存储的 Documents 之间的关系是两者相似或者相关;这个和关系型数据库中的设计理念有极大的不同;其关系如下图所示,一个 Collection 可以包含多个结构相似的 Documents;

Database

Database 就是一系列 Collections 的容器了;每个不同的 Database 在磁盘上都拥有自己所特有的文件集合;通常一个 MongoDB 包含多个 Databases;

与 RDBMS 的对别

上图摘取自 tutorialspoint,大部分都赞同,但是对 Table join 就是 Embedded Documents 的说法持保留意见;

Reference

https://docs.mongodb.com/manual/introduction/
https://www.tutorialspoint.com/mongodb/mongodb_overview.htm