Databases & Collections
What is a Database?
Section titled “What is a Database?”In the MSSQL universe, we have a Database. Good news: In MongoDB, we also have a Database.
- SQL Database: A container for tables, views, stored procedures, etc.
- MongoDB Database: A container for collections.
Switching Databases
Section titled “Switching Databases”When we first connect, we land in a default database (like test). To start working, we need to switch into our specific database universe.
We use the use command to switch contexts.
use node2knowWe should see: switched to db node2know.
The database doesn’t technically exist yet. MongoDB utilizes Lazy Creation. The hallway isn’t built until we put a box in it.
What is a Collection?
Section titled “What is a Collection?”Now that we are inside our node2know database, we need a place to store data.
In the MSSQL universe, the closest analog to a Mongo Collection is a Table.
- SQL Table: A rigid structure with defined columns and types.
- MongoDB Collection: A flexible container for documents.
The key difference? A collection is Schemaless by default. In a SQL table, every row must follow the same rules (columns). In a MongoDB collection, every document can have a completely different structure if we wanted (though for sanity, we usually keep them similar).
The Explicit vs. Implicit Approach
Section titled “The Explicit vs. Implicit Approach”Option A: Implicit (The Cowboy Way)
Section titled “Option A: Implicit (The Cowboy Way)”Just insert a document into a collection that doesn’t exist, and MongoDB will create it for us.
db.users.insertOne({ name: "Solo" });
Fig 1: Inserting a document into a collection that doesn’t exist.
Option B: Explicit (The Architect Way)
Section titled “Option B: Explicit (The Architect Way)”We can create a collection manually if we want to set specific rules (validation, capped size, etc.).
db.createCollection("students");For our purposes, we will stick to the Architect Way to be intentional.
db.createCollection("projects");Verify it exists:
show collections
Fig 2: Show collections.
⏭ Inserting Documents
Section titled “⏭ Inserting Documents”Stashing our first digital assets using insertOne({}) and insertMany([]).