简介
MongoDB 是一种流行的 NoSQL 数据库,而 Node.js 驱动(如 mongodb
包)为开发者提供了与数据库交互的便捷方式。通过本教程,你将学习如何在 Node.js 项目中使用 MongoDB 驱动进行数据操作。
安装与配置
- 安装 MongoDB
确保你的系统已安装 MongoDB,可参考 MongoDB 官方安装指南。 - 安装 Node.js 驱动
使用 npm 安装驱动:npm install mongodb
- 连接数据库
示例代码:const { MongoClient } = require('mongodb'); const uri = 'mongodb://localhost:27017'; const client = new MongoClient(uri);
基本操作
- 插入数据
const collection = client.db("test").collection("documents"); await collection.insertOne({ name: "Example", value: 1 });
- 查询数据
const result = await collection.find({ name: "Example" }).toArray(); console.log(result);
- 更新数据
await collection.updateOne({ name: "Example" }, { $set: { value: 2 } });
- 删除数据
await collection.deleteOne({ name: "Example" });
高级功能
- 索引优化
创建索引提升查询效率:await collection.createIndex({ name: 1 }, { name: "nameIndex" });
- 聚合操作
使用聚合框架进行复杂数据处理:const aggregateResult = await collection.aggregate([ { $match: { value: { $gt: 1 } } }, { $group: { _id: null, total: { $sum: "$value" } } } ]).toArray();
- 事务支持
启用事务确保数据一致性:await client.startSession();
常见问题
- 如何连接远程 MongoDB 服务?
参考 MongoDB 连接配置文档。 - 驱动版本兼容性问题?
请查看 Node.js 驱动 GitHub 仓库 的发布说明。