Skip to content

MongoDB Document 存储

简单 约 15 分钟

你将构建什么

设置的 MongoDB 操作那个创建 blog 集合使用 flexible documents, 查询通过 embedded 字段, and 更新 nested 数据.

学习目标

  • Insert flexible documents 使用 varying 字段
  • 查询通过 embedded and nested 字段
  • 更新 nested document 字段
  • 理解 differences 从 relational 设计

前置要求

  • 基础理解的 JSON
  • 数据库概念
  • NoSQL overview

步骤

  1. 1

    Insert blog posts as documents

    Insert two blog post documents. Notice 它们有 不同字段 — 否 fixed Schema 必需.

    代码
    db.posts.insertOne({
      title: "Learning SQL",
      author: { name: "Ada", email: "[email protected]" },
      tags: ["sql", "database"],
      views: 142,
      published: true
    });
    
    db.posts.insertOne({
      title: "NoSQL Basics",
      author: { name: "Grace", role: "admin" },
      tags: ["nosql", "mongodb"],
      views: 89,
      published: true,
      featured: true  // this field doesn't exist in the first doc
    });

    预期结果

    Two documents 是 inserted 使用不同字段设置.

  2. 2

    查询通过 nested 字段

    查找所有 posts 通过特定 author 通过 querying nested author.name 字段.

    代码
    db.posts.find({ "author.name": "Ada" });

    预期结果

    返回 post authored 通过 Ada.

  3. 3

    查询通过数组元素

    查找所有 posts 那个有 特定标签. MongoDB 能查询内部数组 directly.

    代码
    db.posts.find({ tags: "sql" });

    预期结果

    返回所有 posts tagged 使用 'sql'.

  4. 4

    更新 nested 字段

    Increment view 数量的 post and 添加新 标签 using MongoDB 更新运算符.

    代码
    db.posts.updateOne(
      { title: "Learning SQL" },
      {
        $inc: { views: 1 },
        $push: { tags: "tutorial" }
      }
    );

    预期结果

    post's views increase 通过 1 and '教程' 是添加到 它的标签.

  5. 5

    添加索引优化查询

    为频繁查询的列创建索引,提升查询性能。索引是数据库性能优化的首要手段,但需注意写操作的开销。

    代码
    -- Create indexes on frequently filtered columns
    CREATE INDEX idx_users_email ON users(email);
    CREATE INDEX idx_orders_user_id ON orders(user_id);
    CREATE INDEX idx_orders_created_at ON orders(created_at DESC);
    
    -- Verify the index is used
    EXPLAIN SELECT * FROM orders WHERE user_id = 42;

    预期结果

    EXPLAIN 输出显示使用 idx_orders_user_id 索引扫描而非全表扫描。

自己动手试试

你学到了什么

你工作使用 MongoDB's flexible document model, querying nested 字段 and 数组, and using 更新运算符 — experiencing 如何 NoSQL differs 从 relational 数据库.

相关资源

相关课程

相关术语

相关术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回主题