名称: mongodb-crud-operations 版本: “2.1.0” 描述: 掌握MongoDB CRUD操作,文档插入、查询、更新和删除。学习BSON格式、ObjectId、数据类型和基本操作。适用于处理文档、集合和基本MongoDB操作时使用。 sasmp_version: “1.3.0” 绑定代理: 01-mongodb-fundamentals 绑定类型: PRIMARY_BOND
生产级技能配置
能力:
- 文档插入
- 文档查询
- 文档更新
- 文档删除
- 批量操作
- 原子操作
输入验证: 必需上下文: - 操作类型 - 集合名称 可选上下文: - 文档模式 - 写关注 - 读偏好
输出格式: 代码示例: 字符串 解释: 字符串 错误处理: 字符串 最佳实践: 数组
错误处理: 常见错误: - 代码: CRUD001 条件: “重复键错误 (11000)” 恢复: “检查唯一索引,如果合适使用upsert” - 代码: CRUD002 条件: “文档验证失败” 恢复: “验证文档是否符合模式验证规则” - 代码: CRUD003 条件: “写关注超时” 恢复: “增加wtimeout或降低写关注级别”
先决条件: mongodb版本: “4.0+” 必需知识: - mongodb-连接 - bson-类型 驱动要求: - “您语言的MongoDB原生驱动”
测试: 单元测试模板: | // 测试CRUD操作 const insertResult = await collection.insertOne(doc) expect(insertResult.insertedId).toBeDefined() const found = await collection.findOne({_id: insertResult.insertedId}) expect(found).toMatchObject(doc)
MongoDB CRUD 操作
掌握基本的MongoDB创建、读取、更新、删除操作。
快速开始
连接到MongoDB
const { MongoClient } = require('mongodb');
const client = new MongoClient('mongodb://localhost:27017');
await client.connect();
const db = client.db('myapp');
const users = db.collection('users');
创建文档
// 插入一个文档
const result = await users.insertOne({
name: 'John Doe',
email: 'john@example.com',
age: 30,
createdAt: new Date()
});
console.log('插入的ID:', result.insertedId);
// 插入多个文档
await users.insertMany([
{ name: 'Alice', email: 'alice@example.com' },
{ name: 'Bob', email: 'bob@example.com' }
]);
读取文档
// 查找一个文档
const user = await users.findOne({ email: 'john@example.com' });
// 查找所有文档
const allUsers = await users.find({}).toArray();
// 带过滤器查找
const activeUsers = await users.find({ status: 'active' }).toArray();
// 通过ObjectId查找
const { ObjectId } = require('mongodb');
const user = await users.findOne({ _id: new ObjectId('...') });
更新文档
// 更新一个文档
const result = await users.updateOne(
{ email: 'john@example.com' },
{ $set: { age: 31, updatedAt: new Date() } }
);
// 更新多个文档
await users.updateMany(
{ status: 'inactive' },
{ $set: { lastNotified: new Date() } }
);
// 替换整个文档
await users.replaceOne(
{ _id: userId },
{ name: 'New Name', email: 'new@example.com' }
);
删除文档
// 删除一个文档
await users.deleteOne({ email: 'john@example.com' });
// 删除多个文档
await users.deleteMany({ status: 'deleted' });
// 删除所有文档(小心!)
await users.deleteMany({});
BSON 数据类型
// 字符串
{ name: 'John' }
// 数字(int32, int64, double)
{ age: 30, price: 19.99 }
// 布尔值
{ isActive: true }
// 日期
{ createdAt: new Date() }
// 数组
{ tags: ['mongodb', 'database', 'nosql'] }
// 对象(嵌入式文档)
{ address: { city: 'New York', zip: '10001' } }
// ObjectId(默认 _id 字段)
{ _id: ObjectId('507f1f77bcf86cd799439011') }
// 空值
{ description: null }
// 二进制数据
{ image: Buffer.from('data') }
// 正则表达式
{ email: /.*@example\.com/ }
关键概念
- _id 字段: 自动生成的ObjectId,唯一标识符
- 集合: SQL中的表等价物
- 文档: JSON-like记录(最大16MB)
- 字段名称: 区分大小写,不能以 $ 开头
- 运算符: $set, $inc, $push, $pull, $unset 等
Python 示例(PyMongo)
from pymongo import MongoClient
from datetime import datetime
client = MongoClient('mongodb://localhost:27017')
db = client['myapp']
users = db['users']
# 插入
result = users.insert_one({
'name': 'John',
'email': 'john@example.com',
'createdAt': datetime.now()
})
# 读取
user = users.find_one({'email': 'john@example.com'})
# 更新
users.update_one(
{'_id': result.inserted_id},
{'$set': {'age': 30}}
)
# 删除
users.delete_one({'_id': result.inserted_id})
最佳实践
✅ 始终使用 try-catch 处理错误 ✅ 使用连接池 ✅ 正确关闭连接 ✅ 为 _id 字段使用 ObjectId ✅ 插入前验证数据 ✅ 使用适当的写关注 ✅ 为频繁查询的字段建立索引 ✅ 规划模式演进