如何向 MongoDB 添加记录

MongoDBBeginner
立即练习

简介

本全面教程将探讨向强大的 NoSQL 数据库 MongoDB 中添加记录的基本技术。无论你是初学者还是有经验的开发者,都将学习如何使用各种方法有效地插入文档,理解插入策略,并优化你在 MongoDB 中的数据管理方法。

MongoDB 基础

什么是 MongoDB?

MongoDB 是一个广受欢迎的 NoSQL 数据库,具有高性能、高可用性和易于扩展的特点。与传统的关系型数据库不同,MongoDB 将数据存储在灵活的、类似 JSON 的文档中,称为 BSON(二进制 JSON),这允许使用更动态且无模式的数据模型。

关键特性

特性 描述
面向文档 数据存储在灵活的文档中
无模式 无需预定义结构
可扩展 支持水平扩展
高性能 支持索引和快速查询

MongoDB 架构

graph TD A[客户端应用程序] --> B[MongoDB 服务器] B --> C[数据库] C --> D[集合] D --> E[文档]

在 Ubuntu 22.04 上安装

要安装 MongoDB,请使用以下命令:

## 导入 MongoDB 公共 GPG 密钥
wget -qO - https://www.mongodb.org/static/pgp/server-6.0.asc | sudo apt-key add -

## 添加 MongoDB 软件源
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/6.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-6.0.list

## 更新软件包列表
sudo apt-get update

## 安装 MongoDB
sudo apt-get install -y mongodb-org

基本概念

数据库

集合的容器,类似于传统系统中的数据库。

集合

一组 MongoDB 文档,相当于关系型数据库中的表。

文档

MongoDB 集合中的一条记录,以 BSON 格式表示。

数据类型

MongoDB 支持多种数据类型:

  • 字符串
  • 整数
  • 双精度浮点数
  • 布尔值
  • 数组
  • 对象
  • 时间戳
  • 日期

启动 MongoDB 服务

## 启动 MongoDB 服务
sudo systemctl start mongod

## 启用 MongoDB 在开机时启动
sudo systemctl enable mongod

## 检查服务状态
sudo systemctl status mongod

连接到 MongoDB

## 启动 MongoDB shell
mongosh

## 列出数据库
show dbs

## 选择一个数据库
use labex_database

通过理解这些基础知识,在你的实验(LabEx)学习之旅中,你将为使用 MongoDB 做好充分准备。

文档插入

文档插入简介

文档插入是 MongoDB 中的一项基本操作,它允许你向集合中添加新记录。MongoDB 提供了多种方法来插入具有不同特性和用例的文档。

基本插入方法

insertOne() 方法

insertOne() 方法允许你将单个文档插入到集合中:

// 基本语法
db.collection.insertOne({
  field1: value1,
  field2: value2
});

// 示例
db.users.insertOne({
  name: "John Doe",
  age: 30,
  email: "john@labex.io"
});

insertMany() 方法

insertMany() 方法允许同时插入多个文档:

// 插入多个文档
db.users.insertMany([
  { name: "Alice", age: 25 },
  { name: "Bob", age: 35 },
  { name: "Charlie", age: 28 }
]);

插入策略

graph TD A[文档插入] --> B[insertOne] A --> C[insertMany] A --> D[有序插入] A --> E[无序插入]

有序插入与无序插入

类型 行为 性能 错误处理
有序 遇到第一个错误即停止 较慢 停止进一步插入
无序 遇到错误后继续 较快 跳过失败的文档

无序插入示例

db.users.insertMany([{ name: "David" }, { name: "Eve" }], { ordered: false });

处理重复键

try {
  db.users.insertOne({
    _id: "唯一标识符",
    name: "Frank"
  });
} catch (error) {
  print("重复键错误:", error);
}

最佳实践

  1. 始终验证文档结构
  2. 使用适当的数据类型
  3. 考虑批量插入的性能
  4. 处理潜在错误
  5. 对复杂插入使用事务

验证与错误处理

function safeInsert(collection, document) {
  try {
    return collection.insertOne(document);
  } catch (error) {
    console.error("插入失败:", error);
    return null;
  }
}

性能考量

  • 对大型数据集进行批量插入
  • 尽可能使用无序插入
  • 实施适当的索引
  • 使用 LabEx 监控工具监控插入性能

实际示例

// 创建一个包含多个文档的 users 集合
db.users.insertMany([
  {
    username: "labex_user1",
    email: "user1@labex.io",
    skills: ["MongoDB", "Node.js"]
  },
  {
    username: "labex_user2",
    email: "user2@labex.io",
    skills: ["Python", "数据科学"]
  }
]);

通过掌握这些文档插入技术,你将能够在 MongoDB 数据库中高效地管理数据。

高级插入

复杂插入技术

MongoDB 中的高级文档插入超越了基本方法,为复杂数据管理和性能优化提供了强大的策略。

批量写操作

graph TD A[批量写] --> B[插入] A --> C[更新] A --> D[删除] A --> E[替换]

实现批量写

const bulkOperations = db.collection.initializeUnorderedBulkOp();

bulkOperations.insert({ name: "LabEx User1" });
bulkOperations.insert({ name: "LabEx User2" });
bulkOperations.execute();

写关注级别

级别 描述 耐久性 性能
0 无确认 最低 最高
1 主节点确认 中等 中等
多数 集群多数 最高 最低

写关注示例

db.users.insertOne(
  { username: "高级用户" },
  {
    writeConcern: {
      w: "多数",
      wtimeout: 5000
    }
  }
);

原子事务

const session = db.getMongo().startSession();
session.startTransaction();

try {
  const usersCollection = session.getDatabase("labex").users;
  const accountsCollection = session.getDatabase("labex").accounts;

  usersCollection.insertOne({
    username: "事务用户"
  });

  accountsCollection.insertOne({
    balance: 1000
  });

  session.commitTransaction();
} catch (error) {
  session.abortTransaction();
}

模式验证

创建经过验证的集合

db.createCollection("users", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["username", "email"],
      properties: {
        username: {
          bsonType: "string",
          description: "用户名必须是字符串"
        },
        email: {
          bsonType: "string",
          pattern: "^.+@.+$",
          description: "需要有效的电子邮件"
        }
      }
    }
  }
});

upsert 操作

Upsert 在单个操作中结合了插入和更新:

db.users.updateOne(
  { username: "labex_user" },
  {
    $set: {
      email: "user@labex.io"
    }
  },
  { upsert: true }
);

性能优化策略

  1. 对并行处理使用 ordered: false
  2. 实施批量插入
  3. 创建适当的索引
  4. 谨慎使用写关注
  5. 利用批量写操作

错误处理与日志记录

function advancedInsert(collection, documents) {
  try {
    const result = collection.insertMany(documents, { ordered: false });
    console.log(`${result.insertedCount} 个文档已插入`);
  } catch (error) {
    console.error("插入错误:", error.writeErrors);
  }
}

监控插入性能

const startTime = Date.now();
db.users.insertMany(largeDocumentArray);
const endTime = Date.now();

console.log(`插入耗时 ${endTime - startTime} 毫秒`);

复杂文档插入

db.courses.insertOne({
  name: "LabEx MongoDB 高级课程",
  instructor: {
    name: "专家培训师",
    credentials: ["MongoDB 认证"]
  },
  modules: [
    { title: "高级插入", difficulty: "高级" },
    { title: "性能优化", difficulty: "专家" }
  ]
});

通过掌握这些高级插入技术,你将充分发挥 MongoDB 在复杂数据管理和高性能应用方面的全部潜力。

总结

通过掌握 MongoDB 记录插入技术,开发者能够灵活且高效地管理和存储数据。本教程涵盖了基本和高级插入方法,深入介绍了在 MongoDB 中创建、插入和操作文档的方法,使你能够充分发挥这个多功能 NoSQL 数据库的潜力。