Skip to content

Databases & Collections

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.

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 node2know

We should see: switched to db node2know.

Lazy Creation

The database doesn’t technically exist yet. MongoDB utilizes Lazy Creation. The hallway isn’t built until we put a box in it.

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).

Just insert a document into a collection that doesn’t exist, and MongoDB will create it for us.

db.users.insertOne({ name: "Solo" });
Inserting a document into a collection that doesn't exist.

Fig 1: Inserting a document into a collection that doesn’t exist.

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
Show collections.

Fig 2: Show collections.

Stashing our first digital assets using insertOne({}) and insertMany([]).