简介
本全面教程将探讨向强大的 NoSQL 数据库 MongoDB 中添加记录的基本技术。无论你是初学者还是有经验的开发者,都将学习如何使用各种方法有效地插入文档,理解插入策略,并优化你在 MongoDB 中的数据管理方法。
本全面教程将探讨向强大的 NoSQL 数据库 MongoDB 中添加记录的基本技术。无论你是初学者还是有经验的开发者,都将学习如何使用各种方法有效地插入文档,理解插入策略,并优化你在 MongoDB 中的数据管理方法。
MongoDB 是一个广受欢迎的 NoSQL 数据库,具有高性能、高可用性和易于扩展的特点。与传统的关系型数据库不同,MongoDB 将数据存储在灵活的、类似 JSON 的文档中,称为 BSON(二进制 JSON),这允许使用更动态且无模式的数据模型。
| 特性 | 描述 |
|---|---|
| 面向文档 | 数据存储在灵活的文档中 |
| 无模式 | 无需预定义结构 |
| 可扩展 | 支持水平扩展 |
| 高性能 | 支持索引和快速查询 |
要安装 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 服务
sudo systemctl start mongod
## 启用 MongoDB 在开机时启动
sudo systemctl enable mongod
## 检查服务状态
sudo systemctl status mongod
## 启动 MongoDB shell
mongosh
## 列出数据库
show dbs
## 选择一个数据库
use labex_database
通过理解这些基础知识,在你的实验(LabEx)学习之旅中,你将为使用 MongoDB 做好充分准备。
文档插入是 MongoDB 中的一项基本操作,它允许你向集合中添加新记录。MongoDB 提供了多种方法来插入具有不同特性和用例的文档。
insertOne() 方法允许你将单个文档插入到集合中:
// 基本语法
db.collection.insertOne({
field1: value1,
field2: value2
});
// 示例
db.users.insertOne({
name: "John Doe",
age: 30,
email: "john@labex.io"
});
insertMany() 方法允许同时插入多个文档:
// 插入多个文档
db.users.insertMany([
{ name: "Alice", age: 25 },
{ name: "Bob", age: 35 },
{ name: "Charlie", age: 28 }
]);
| 类型 | 行为 | 性能 | 错误处理 |
|---|---|---|---|
| 有序 | 遇到第一个错误即停止 | 较慢 | 停止进一步插入 |
| 无序 | 遇到错误后继续 | 较快 | 跳过失败的文档 |
db.users.insertMany([{ name: "David" }, { name: "Eve" }], { ordered: false });
try {
db.users.insertOne({
_id: "唯一标识符",
name: "Frank"
});
} catch (error) {
print("重复键错误:", error);
}
function safeInsert(collection, document) {
try {
return collection.insertOne(document);
} catch (error) {
console.error("插入失败:", error);
return null;
}
}
// 创建一个包含多个文档的 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 中的高级文档插入超越了基本方法,为复杂数据管理和性能优化提供了强大的策略。
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 在单个操作中结合了插入和更新:
db.users.updateOne(
{ username: "labex_user" },
{
$set: {
email: "user@labex.io"
}
},
{ upsert: true }
);
ordered: falsefunction 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 数据库的潜力。