MongoDB cơ bản: khái niệm và công cụ
MongoDB là cơ sở dữ liệu NoSQL hướng tài liệu: dữ liệu lưu dưới dạng document giống JSON thay vì bảng và hàng.
Khái niệm cốt lõi
| MongoDB | SQL tương đương | Ý nghĩa |
|---|---|---|
| Database | Database | Chứa nhiều collection |
| Collection | Table | Nhóm các document liên quan |
| Document | Row | Một bản ghi (lưu dạng BSON) |
| Field | Column | Một cặp khóa - giá trị |
Mỗi document có trường _id duy nhất (tự sinh ObjectId nếu bạn không cung cấp). Các document trong cùng collection không bắt buộc có cấu trúc giống nhau.
{
"_id": ObjectId("665f1c2e8a1b2c3d4e5f6a7b"),
"name": "Linh",
"email": "linh@example.com",
"skills": ["javascript", "mongodb"],
"address": { "city": "Ho Chi Minh City" }
}
CRUD
// Create
db.users.insertOne({ name: "Linh", email: "linh@example.com", age: 27 });
// Read
db.users.find({ age: { $gte: 25 } }, { name: 1, _id: 0 });
// Update
db.users.updateOne({ email: "linh@example.com" }, { $set: { age: 28 } });
// Delete
db.users.deleteOne({ email: "linh@example.com" });
Kiểm tra filter bằng
find()trước khi chạyupdateMany()hoặcdeleteMany(). Filter rỗng{}sẽ ảnh hưởng toàn bộ collection.
Index và Aggregation
// Unique index; check the plan with explain() (look for IXSCAN, not COLLSCAN)
db.users.createIndex({ email: 1 }, { unique: true });
db.users.find({ email: "linh@example.com" }).explain("executionStats");
// Aggregation pipeline: top 5 customers by total spent
db.orders.aggregate([
{ $match: { status: "completed" } },
{ $group: { _id: "$customerId", total: { $sum: "$amount" } } },
{ $sort: { total: -1 } },
{ $limit: 5 }
]);
Embedding hay Referencing
- Embedding: nhúng dữ liệu liên quan vào cùng document. Đọc nhanh, phù hợp khi dữ liệu luôn được đọc cùng nhau.
- Referencing: lưu
_idcủa document khác. Phù hợp với quan hệ 1-nhiều, nhiều-nhiều hoặc dữ liệu đổi thường xuyên.
Hãy thiết kế schema theo cách ứng dụng truy vấn dữ liệu.
Các công cụ chính
| Công cụ | Dùng để |
|---|---|
| mongosh | Shell dòng lệnh để chạy lệnh và script |
| Compass | Giao diện desktop: xem dữ liệu, truy vấn, tạo index, dựng aggregation |
| Atlas | MongoDB chạy trên cloud, được quản lý hoàn toàn |
| Database Tools | mongodump/mongorestore (sao lưu), mongoimport/mongoexport (nhập/xuất) |
| VS Code extension | Duyệt và truy vấn dữ liệu ngay trong VS Code |
# Connect with mongosh (the password is prompted, so it stays out of shell history)
mongosh "mongodb+srv://<cluster-host>/<database>" --username <username>
Atlas trong 4 bước
- Tạo cluster (gói Free dùng để học, không dùng cho production).
- Database Access: tạo database user với quyền tối thiểu.
- Network Access: thêm IP của bạn vào danh sách cho phép, tránh
0.0.0.0/0. - Lấy connection string rồi dán vào Compass, mongosh hoặc code.
Kết nối từ Node.js an toàn
Connection string chứa mật khẩu nên phải để trong biến môi trường, và file .env phải nằm trong .gitignore.
/**
* File: db.js
* Created: 2026-11-08
* Author: The Vi
* Description: Creates a reusable MongoDB connection from an environment variable.
*/
require("dotenv").config();
const { MongoClient } = require("mongodb");
const uri = process.env.MONGODB_URI;
if (!uri) {
throw new Error("MONGODB_URI is not set");
}
// Reuse one client for the whole app
const client = new MongoClient(uri);
async function getDb() {
await client.connect();
return client.db(process.env.MONGODB_DB_NAME || "mydb");
}
module.exports = { getDb };
Bảo mật: 5 điều cần nhớ
- Không đưa connection string vào mã nguồn hoặc frontend.
- Mỗi ứng dụng một database user riêng, quyền tối thiểu.
- Giới hạn IP truy cập, không mở cổng
27017ra Internet công khai. - Validate và ép kiểu input để tránh NoSQL injection (ví dụ từ chối nếu
typeof email !== "string"). - Sao lưu định kỳ và thử khôi phục thật.
Kết luận
Nắm vững mô hình database → collection → document, biết dùng index và aggregation, chọn embedding hay referencing theo cách đọc dữ liệu. Về công cụ, bắt đầu với mongosh, Compass và Atlas, rồi thêm Database Tools khi cần sao lưu và nhập/xuất dữ liệu.