MongoDB API 详解:从核心操作到高级功能
MongoDB 提供了丰富的 API 接口,支持多种编程语言和场景。以下是其核心功能的详解,涵盖基础操作、高级查询、事务处理及管理接口。
一、核心 API 分类
1. 连接与配置
- 驱动连接(以 Node.js 为例):
const { MongoClient } = require('mongodb'); const uri = 'mongodb://localhost:27017'; const client = new MongoClient(uri); await client.connect();
- 连接池配置:
const client = new MongoClient(uri, { maxPoolSize: 100, minPoolSize: 10, waitQueueTimeoutMS: 5000 });
2. CRUD 操作
- 插入文档:
await db.collection('users').insertOne({ name: 'Alice', age: 30, email: 'alice@example.com' });
- 查询文档:
// 精确匹配 const user = await db.collection('users').findOne({ _id: new ObjectId('65a1b2c3d4e5f60000000001') }); // 条件查询 const users = await db.collection('users').find({ age: { $gt: 25 } }).toArray();
- 更新文档:
await db.collection('users').updateOne( { _id: user._id }, { $set: { age: 31 }, $inc: { loginCount: 1 } } );
- 删除文档:
await db.collection('users').deleteOne({ _id: user._id });
3. 聚合管道
- 基础聚合:
const results = await db.collection('orders').aggregate([ { $match: { status: 'shipped' } }, { $group: { _id: '$customer_id', total: { $sum: '$amount' } } }, { $sort: { total: -1 } } ]).toArray();
- 高级操作:
// 窗口函数(MongoDB 5.0+) { $setWindowFields: { sortBy: { createdAt: 1 }, output: { rowNumber: { $rowNumber: {} }, rank: { $rank: {} } } } }
二、高级功能 API
1. 事务处理
- 单文档事务(自动提交):
await db.collection('accounts').updateOne( { _id: 'A' }, { $inc: { balance: -100 } } );
- 多文档事务(副本集/分片集群):
const session = client.startSession(); try { await session.withTransaction(async () => { await db.collection('accounts').updateOne( { _id: 'A' }, { $inc: { balance: -100 } }, { session } ); await db.collection('accounts').updateOne( { _id: 'B' }, { $inc: { balance: 100 } }, { session } ); }); } finally { await session.endSession(); }
2. 索引管理
- 创建索引:
// 单字段索引 await db.collection('users').createIndex({ email: 1 }); // 复合索引 await db.collection('orders').createIndex({ customer_id: 1, status: -1 }); // TTL 索引(自动删除过期数据) await db.collection('logs').createIndex({ createdAt: 1 }, { expireAfterSeconds: 86400 });
- 索引优化:
// 查看索引使用情况 const stats = await db.collection('users').aggregate([ { $indexStats: {} } ]).toArray();
3. 变更流(Change Streams)
- 监听集合变更:
const pipeline = [ { $match: { operationType: { $in: ['insert', 'update'] } } } ]; const changeStream = db.collection('users').watch(pipeline); changeStream.on('change', (next) => { console.log('变更事件:', next); });
- 分片集群支持:
// 监听整个数据库的变更 const dbChangeStream = client.db('ecommerce').watch();
三、管理 API
1. 用户与权限
- 创建用户:
await db.admin().command({ createUser: 'app_user', pwd: 'SecurePass123!', roles: [ { role: 'readWrite', db: 'ecommerce' }, { role: 'read', db: 'logs' } ] });
- 角色管理:
// 创建自定义角色 await db.admin().command({ createRole: 'analytics_user', privileges: [ { resource: { db: 'ecommerce', collection: 'orders' }, actions: ['find', 'aggregate'] } ], roles: [] });
2. 副本集与分片管理
- 副本集状态:
const status = await db.admin().command({ replSetGetStatus: 1 });
- 分片配置:
// 启用分片 await db.admin().command({ enableSharding: 'ecommerce' }); // 对集合分片 await db.admin().command({ shardCollection: 'ecommerce.orders', key: { customer_id: 1 } });
四、性能优化 API
1. 解释计划
- 查询分析:
const plan = await db.collection('users').find({ age: { $gt: 25 } }).explain(); console.log(plan.queryPlanner.winningPlan);
2. 性能监控
- 服务器状态:
const serverStatus = await db.admin().command({ serverStatus: 1 }); console.log(`连接数: ${serverStatus.connections.current}`);
- 锁统计:
const locks = serverStatus.locks; console.log(`全局写锁占比: ${(locks.global.acquireWaitCount.R / serverStatus.uptime) * 100}%`);
五、最佳实践
-
连接管理:
- 使用连接池避免频繁开销。
- 生产环境启用 TLS 加密:
const client = new MongoClient(uri, { tls: true, tlsCAFile: '/etc/mongo/ca.pem' });
-
错误处理:
- 捕获特定异常(如
MongoServerError
):try { await db.collection('users').insertOne({}); } catch (err) { if (err instanceof MongoServerError && err.code === 11000) { console.log('重复键错误'); } }
- 捕获特定异常(如
-
索引策略:
- 避免过度索引(每个集合不超过 5 个)。
- 定期重建索引:
await db.collection('users').reIndex();
六、生态扩展
1. 官方工具链
- MongoDB Shell:交互式查询与管理。
- Compass:可视化建模与性能分析。
2. 驱动与 ORM
- Node.js:
mongodb
包(官方驱动)。 - Python:
PyMongo
+MongoEngine
(ODM)。 - Java:
MongoDB Async Driver
(非阻塞IO)。
3. 云服务集成
- MongoDB Atlas:
- 自动扩展存储与计算资源。
- 内置备份、监控与 AI 功能(如 NLP 搜索)。
七、总结
MongoDB API 通过丰富的接口覆盖了从基础 CRUD 到高级事务、索引优化的全场景需求。其设计哲学包括:
- 灵活性:支持动态模式与多语言驱动。
- 可扩展性:分片集群与变更流应对海量数据。
- 安全性:TLS 加密、细粒度权限控制。
开发者可根据业务需求选择合适的 API 组合,并结合官方工具链提升开发效率。例如,电商系统可利用聚合管道实现实时数据分析,金融应用则可通过事务 API 保障资金操作的一致性。