MongoDB - 概述
MongoDB - 概述
Section titled “MongoDB - 概述”MongoDB 是一个跨平台、面向文档的 NoSQL 数据库。它专为高性能、高可用性和易扩展性而设计。与关系型数据库以表和行存储数据不同,MongoDB 将数据存储在灵活的、类似 JSON 的文档中。
数据库是集合的物理容器。每个数据库在文件系统上都有自己的一组文件。单个 MongoDB 服务器可以托管多个数据库。
集合是 MongoDB 文档的组,大致相当于关系型数据库(RDBMS)中的表。一个集合存在于单个数据库中。集合默认不强制执行模式,这意味着集合中的文档可以拥有不同的字段。
文档是一组键值对,以 BSON(二进制 JSON)格式存储。BSON 扩展了 JSON,增加了额外的BSON数据类型,如 ObjectId、Date 和 Int64,以优化存储和速度。文档具有动态模式,允许丰富的分层数据结构。
MongoDB 与 RDBMS 术语对照
Section titled “MongoDB 与 RDBMS 术语对照”下表显示了 RDBMS 术语与 MongoDB 术语之间的关系。
| RDBMS | MongoDB |
|---|---|
| Database | Database |
| Table | Collection |
| Row | Document |
| Column | Field |
| Table Join | Embedded Documents / Lookups ($lookup) |
| Primary Key | Primary Key (Default key _id provided by MongoDB) |
| Server | mongod (The database process) |
| Client | mongosh (The MongoDB Shell) |
以下示例展示了一个博客文章的文档结构,使用了 BSON 数据类型。
{ "_id": ObjectId("64f8a00e23e8b1e1ab123456"), "title": "Understanding Modern MongoDB", "content": "MongoDB is a powerful NoSQL database...", "author_username": "tech_writer_jane", "url": "/blog/modern-mongodb", "tags": ["mongodb", "database", "nosql", "webdev"], "published_at": ISODate("2023-09-06T10:00:00Z"), "stats": { "likes": 150, "views": 4500 }, "comments": [ { "user": "reader_dave", "text": "Great article! Very helpful.", "posted_at": ISODate("2023-09-06T11:30:00Z"), "likes": 12 }, { "user": "dev_sara", "text": "Could you add more on indexing?", "posted_at": ISODate("2023-09-07T14:22:00Z"), "likes": 5 } ]}_id 字段是一个 12 字节的 BSON 类型,保证文档的唯一性。如果未提供,它会自动由 MongoDB 生成。这 12 字节由以下部分组成:一个 4 字节的时间戳、一个 5 字节的随机值和一个 3 字节的递增计数器。
现代部署:MongoDB Atlas
Section titled “现代部署:MongoDB Atlas”虽然您可以在自己的服务器上运行 MongoDB,但大多数现代应用程序都利用基于云的数据库即服务(DBaaS)解决方案。MongoDB Atlas 是官方的托管数据库服务,负责处理基础设施、扩展、备份和安全性,使开发人员能够专注于构建应用程序。