You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
The two fundamental building blocks of MongoDB are documents and collections. Understanding these concepts deeply will help you design efficient data models from the start.
A MongoDB document is a set of field-value pairs stored in BSON format. Every document must have a top-level _id field that uniquely identifies it within its collection. If you do not supply _id when inserting, MongoDB automatically generates an ObjectId.
{
_id: ObjectId("64b2e3f1a2b3c4d5e6f70001"),
title: "Getting Started with MongoDB",
author: "Jane Smith",
tags: ["mongodb", "nosql", "database"],
publishedAt: new Date("2024-03-15"),
stats: {
views: 4200,
likes: 318
}
}
Documents can contain nested documents (embedded documents) and arrays, allowing you to represent rich, hierarchical data in a single record. This is one of the most powerful aspects of the document model.
MongoDB supports all standard JSON types — String, Number, Boolean, Array, Object, and Null — plus BSON-specific types:
A collection is a group of documents, analogous to a table in a relational database. Collections do not enforce a schema by default, meaning documents within the same collection can have different fields.
// Both documents can coexist in the same "products" collection
{ _id: 1, name: "T-Shirt", size: "M", colour: "blue" }
{ _id: 2, name: "Laptop", ram: "16GB", storage: "512GB SSD" }
Collections are created implicitly the first time you insert a document into them. There is no CREATE TABLE equivalent needed.
Above collections sits the database level. A single MongoDB server (or cluster) can host many databases, each containing its own set of collections. Databases are also created implicitly.
use myapp // switch to (or create) the myapp database
db.users.find() // access the users collection
Although MongoDB is schema-flexible, you can enforce structure using JSON Schema validation rules applied to a collection. This gives you the best of both worlds: flexibility where needed, constraints where critical.
db.createCollection("orders", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["customerId", "total"],
properties: {
total: { bsonType: "decimal" }
}
}
}
})
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.