mongodb-usage

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

MongoDB Best Practices

MongoDB最佳实践

MCP Limitation

MCP限制

This MCP operates in READ-ONLY mode. No write, update, or delete operations are possible.
本MCP以只读模式运行。 无法执行写入、更新或删除操作。

Schema Design Patterns

架构设计模式

Embedding vs Referencing

嵌入 vs 引用

Embed when:
  • Data is accessed together frequently
  • Child documents are bounded (won't grow unbounded)
  • One-to-few relationships
  • Data doesn't change frequently
Reference when:
  • Data is accessed independently
  • Many-to-many relationships
  • Documents would exceed 16MB limit
  • Frequent updates to referenced data
选择嵌入的场景:
  • 数据经常被一起访问
  • 子文档大小有限(不会无限增长)
  • 一对少的关系
  • 数据不经常变更
选择引用的场景:
  • 数据被独立访问
  • 多对多关系
  • 文档大小接近16MB限制
  • 被引用的数据需要频繁更新

Common Patterns

常见模式

Subset pattern: Store frequently accessed subset in parent, full data in separate collection.
Bucket pattern: Group time-series data into buckets (e.g., hourly readings in one document).
Computed pattern: Store pre-computed values for expensive calculations.
子集模式: 在父文档中存储频繁访问的子集,完整数据存储在单独的集合中。
桶模式: 将时间序列数据分组到桶中(例如,将每小时的读数存储在一个文档中)。
计算模式: 存储预计算的值,避免昂贵的计算操作。

Index Strategies

索引策略

Index Guidelines

索引指南

  • Index fields used in queries, sorts, and aggregation $match stages
  • Compound indexes support queries on prefix fields
  • Covered queries (all fields in index) are fastest
  • Too many indexes slow writes
  • 为查询、排序和聚合$match阶段中使用的字段创建索引
  • 复合索引支持对前缀字段的查询
  • 覆盖查询(所有字段都在索引中)速度最快
  • 过多的索引会降低写入性能

Index Types

索引类型

  • Single field: Basic index on one field
  • Compound: Multiple fields, order matters for queries
  • Multikey: Automatically created for array fields
  • Text: Full-text search on string content
  • TTL: Auto-expire documents after time period
  • 单字段索引: 基于单个字段的基础索引
  • 复合索引: 包含多个字段,字段顺序对查询至关重要
  • 多键索引: 为数组字段自动创建
  • 文本索引: 对字符串内容进行全文搜索
  • TTL索引: 在一段时间后自动过期文档

ESR Rule

ESR规则

For compound indexes, order fields by:
  1. Equality (exact match fields)
  2. Sort (sort order fields)
  3. Range (range query fields like $gt, $lt)
对于复合索引,按以下顺序排列字段:
  1. Equality(精确匹配字段)
  2. Sort(排序字段)
  3. Range(范围查询字段,如$gt、$lt)

Aggregation Pipeline

聚合管道

Performance Tips

性能优化技巧

  • Put
    $match
    and
    $project
    early to reduce documents
  • Use
    $limit
    early when possible
  • Avoid
    $lookup
    on large collections without indexes
  • Use
    $facet
    for multiple aggregations in one query
  • 尽早使用
    $match
    $project
    来减少文档数量
  • 尽可能早地使用
    $limit
  • 避免在没有索引的大型集合上使用
    $lookup
  • 使用
    $facet
    在一次查询中执行多个聚合操作

Common Stages

常见阶段

javascript
// Filter documents
{ $match: { status: "active" } }

// Reshape documents
{ $project: { name: 1, total: { $sum: "$items.price" } } }

// Group and aggregate
{ $group: { _id: "$category", count: { $sum: 1 } } }

// Sort results
{ $sort: { count: -1 } }

// Join collections
{ $lookup: { from: "orders", localField: "_id", foreignField: "userId", as: "orders" } }
javascript
// Filter documents
{ $match: { status: "active" } }

// Reshape documents
{ $project: { name: 1, total: { $sum: "$items.price" } } }

// Group and aggregate
{ $group: { _id: "$category", count: { $sum: 1 } } }

// Sort results
{ $sort: { count: -1 } }

// Join collections
{ $lookup: { from: "orders", localField: "_id", foreignField: "userId", as: "orders" } }

Connection Best Practices

连接最佳实践

Connection String Formats

连接字符串格式

  • Atlas:
    mongodb+srv://user:pass@cluster.mongodb.net/database
  • Local:
    mongodb://localhost:27017/database
  • Replica set:
    mongodb://host1,host2,host3/database?replicaSet=rs0
  • Atlas:
    mongodb+srv://user:pass@cluster.mongodb.net/database
  • 本地:
    mongodb://localhost:27017/database
  • 副本集:
    mongodb://host1,host2,host3/database?replicaSet=rs0

Connection Pooling

连接池

  • Use connection pooling in applications (default in drivers)
  • Set appropriate pool size for your workload
  • Don't create new connections per request
  • 在应用中使用连接池(驱动默认支持)
  • 根据工作负载设置合适的池大小
  • 不要为每个请求创建新连接

Anti-Patterns to Avoid

需避免的反模式

  • Unbounded arrays: Arrays that grow without limit
  • Massive documents: Documents approaching 16MB
  • Too many collections: Use embedding instead
  • Missing indexes: Queries doing collection scans
  • $where operator: Use aggregation instead for security
  • Storing files in documents: Use GridFS for large files
  • 无限增长的数组: 没有大小限制的数组
  • 超大文档: 大小接近16MB的文档
  • 过多集合: 优先使用嵌入方式
  • 缺失索引: 执行全集合扫描的查询
  • $where操作符: 出于安全考虑,使用聚合替代
  • 在文档中存储文件: 对大文件使用GridFS