Node.js 操作 MongoDB:CRUD 与聚合查询
·
Node.js 操作 MongoDB:CRUD 与聚合查询
1. 环境准备
- 安装 MongoDB 驱动:
npm install mongodb - 连接数据库:
const { MongoClient } = require("mongodb"); const uri = "mongodb://localhost:27017"; const client = new MongoClient(uri); async function connect() { await client.connect(); return client.db("mydb"); }
2. CRUD 操作
(1) 创建(Create)
async function createUser(db) {
const users = db.collection("users");
const newUser = { name: "Alice", age: 28, role: "admin" };
const result = await users.insertOne(newUser);
console.log("插入ID:", result.insertedId);
}
(2) 读取(Read)
async function findUsers(db) {
const users = db.collection("users");
// 查询所有文档
const allUsers = await users.find().toArray();
// 条件查询:年龄大于25
const filteredUsers = await users.find({ age: { $gt: 25 } }).toArray();
}
(3) 更新(Update)
async function updateUser(db) {
const users = db.collection("users");
// 更新第一个匹配文档
await users.updateOne(
{ name: "Alice" },
{ $set: { age: 30 } }
);
// 更新所有匹配文档
await users.updateMany(
{ role: "admin" },
{ $inc: { age: 1 } } // 年龄+1
);
}
(4) 删除(Delete)
async function deleteUser(db) {
const users = db.collection("users");
// 删除单个文档
await users.deleteOne({ name: "Alice" });
// 删除所有匹配文档
await users.deleteMany({ role: "guest" });
}
3. 聚合查询
聚合管道用于多阶段数据处理,例如:
async function aggregateData(db) {
const orders = db.collection("orders");
const pipeline = [
{ $match: { status: "completed" } }, // 阶段1:过滤数据
{ $group: {
_id: "$product",
total: { $sum: "$amount" } // 阶段2:按产品分组求和
}},
{ $sort: { total: -1 } } // 阶段3:按总和降序排序
];
const result = await orders.aggregate(pipeline).toArray();
console.log(result);
}
输出示例:
[
{ "_id": "Laptop", "total": 4500 },
{ "_id": "Phone", "total": 3200 }
]
4. 完整示例
(async () => {
const db = await connect();
// CRUD 操作
await createUser(db);
await findUsers(db);
await updateUser(db);
await deleteUser(db);
// 聚合查询
await aggregateData(db);
await client.close();
})();
关键概念说明
-
操作符:
- 查询:
$gt(大于)、$in(包含) - 更新:
$set(赋值)、$inc(增量) - 聚合:
$sum(求和)、$sort(排序)
- 查询:
-
性能优化:
- 对频繁查询字段创建索引:
await db.collection("users").createIndex({ age: 1 }); - 聚合时优先使用
$match减少数据处理量
- 对频繁查询字段创建索引:
提示:使用
try/catch处理异步错误,实际部署时需添加环境变量管理数据库凭证。
更多推荐
所有评论(0)