MongoDB là document database: thay vì bảng/dòng như SQL, nó dùng collection (nhóm) chứa các document (giống object JSON). Mỗi document trong cùng collection có thể có cấu trúc khác nhau.
Vài điểm cốt lõi:
- Lưu dưới dạng BSON (Binary JSON) — như JSON nhưng có thêm kiểu Date, ObjectId, Binary.
- Mỗi document tự có _id kiểu ObjectId (12 byte: timestamp + machine + PID + counter) → duy nhất mà không cần bộ điều phối trung tâm.
Schema linh hoạt rất tiện khi cấu trúc hay đổi (catalog mỗi loại sản phẩm có thuộc tính khác nhau), nhưng dễ hại khi cần nhất quán: cùng field age chỗ lưu chuỗi '25', chỗ lưu số 25 → bug khó tìm.
Lưu ý hay gặp: thiếu index → quét toàn collection. Khi cần ép cấu trúc, dùng schema validation $jsonSchema (MongoDB 3.6+).
MongoDB is a document database: instead of SQL tables/rows, it uses collections (groups) holding documents (like JSON objects). Each document in the same collection can have a different structure.
A few core points:
- Stored as BSON (Binary JSON) — like JSON but with extra types Date, ObjectId, Binary.
- Each document auto-gets an _id of type ObjectId (12 bytes: timestamp + machine + PID + counter) → unique without a central coordinator.
Flexible schema is handy when structure changes often (a catalog where each product type has different attributes), but risky when you need consistency: the same age field might store the string '25' in one doc and the number 25 in another → hard-to-find bugs.
Common pitfall: missing indexes → full collection scans. To enforce structure when needed, use schema validation $jsonSchema (MongoDB 3.6+).