mongodb

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

MongoDB

MongoDB

MongoDB is a document database. It stores data in JSON-like documents (BSON). It is the most popular NoSQL database, known for flexibility and scalability.
MongoDB是一款文档型数据库,它以类JSON的BSON格式存储数据。作为最受欢迎的NoSQL数据库,它以灵活性和可扩展性著称。

When to Use

适用场景

  • Rapid Prototyping: Schema-less design allows iterating fast without migrations.
  • Content Management: Storing diverse assets with varying metadata.
  • Catalogs: Product catalogs where each product has different attributes (size, color, wattage).
  • 快速原型开发:无Schema设计允许无需迁移即可快速迭代。
  • 内容管理:存储具有不同元数据的多样化资产。
  • 产品目录:适用于每个产品具有不同属性(尺寸、颜色、功率)的产品目录场景。

Quick Start

快速开始

javascript
// Using Mongoose (Node.js)
const kittySchema = new mongoose.Schema({
  name: String,
});
const Kitten = mongoose.model("Kitten", kittySchema);

const silence = new Kitten({ name: "Silence" });
await silence.save();
javascript
// Using Mongoose (Node.js)
const kittySchema = new mongoose.Schema({
  name: String,
});
const Kitten = mongoose.model("Kitten", kittySchema);

const silence = new Kitten({ name: "Silence" });
await silence.save();

Core Concepts

核心概念

Documents (BSON)

文档(BSON)

Data is stored in "documents" (JSON objects) inside "collections" (Tables).
{ "_id": 1, "name": "Apple", "price": 10 }
数据存储在“集合”(对应关系型数据库的表)中的“文档”(JSON对象)里。
{ "_id": 1, "name": "Apple", "price": 10 }

Embedded Data vs References

嵌入式数据 vs 引用数据

  • Embed: Store related data inside the document for fast reads. (e.g., Comments inside a Post).
  • Reference: Store the ID and look it up (
    $lookup
    ) for many-to-many relationships.
  • 嵌入:将相关数据存储在文档内部,以实现快速读取。(例如,将评论嵌入到帖子文档中)。
  • 引用:存储ID并通过
    $lookup
    查询,适用于多对多关系。

Sharding

分片

MongoDB scales horizontally by splitting data across multiple servers (shards) based on a "shard key".
MongoDB通过基于“分片键”将数据拆分到多个服务器(分片)来实现水平扩展。

Best Practices (2025)

2025年最佳实践

Do:
  • Use Version 8.0+: For performance gains in time-series and queryable encryption.
  • Index Early: "Compass" (GUI) or "Atlas Performance Advisor" will tell you when you miss indexes.
  • Limit Array Growth: Don't use unbounded arrays (e.g., logging every login in the user document).
Don't:
  • Don't join everything: MongoDB supports
    $lookup
    (JOINS), but overuse kills performance. Embed data if accessed together.
  • Don't ignore Document Size: Max document size is 16MB.
建议做法
  • 使用8.0+版本:在时间序列和可查询加密方面获得性能提升。
  • 提前创建索引:Compass(图形界面工具)或Atlas性能顾问会提示您缺少哪些索引。
  • 限制数组增长:不要使用无界数组(例如,在用户文档中记录每次登录日志)。
不建议做法
  • 不要过度关联:MongoDB支持
    $lookup
    (关联查询),但过度使用会影响性能。如果数据是一起访问的,建议嵌入存储。
  • 不要忽略文档大小限制:文档最大大小为16MB。

References

参考资料