LearnAI ToolsCareerPractice BuildsPlayContact
Lesson 1013 min read

Creating Databases & Collections

Create databases and collections explicitly, and understand capped collections and collection options.

Switching to (or Creating) a Database

The use command switches the shell's context to a database, creating it implicitly the first time data is actually written to it.

use blog_app;
db; // shows the current database name

Creating a Collection Explicitly

While inserting a document auto-creates its collection, createCollection() lets you create one explicitly upfront, with configuration options like validation rules (covered in the schema validation lesson).

db.createCollection("posts");
show collections;

Capped Collections

A capped collection has a fixed maximum size, automatically overwriting its oldest documents once full — useful for logging or caching scenarios where you only care about the most recent entries.

db.createCollection("logs", {
capped: true,
size: 5242880, // 5MB, required
max: 5000, // optional max document count
});

Dropping Databases & Collections

db.posts.drop(); // removes the "posts" collection and all its documents
db.dropDatabase(); // removes the entire current database
Both Are Irreversible

Neither drop() nor dropDatabase() asks for confirmation — always double-check which database/collection you're currently connected to before running either.

FAQs

No — for everyday use, letting MongoDB create a collection implicitly on first insert is perfectly normal; explicit creation matters mainly when you need specific options like validation or capped behavior upfront.

Yes — db.collection.renameCollection("newName") renames it in place, without needing to recreate or migrate its documents.

Summary

Databases and collections can be created implicitly or explicitly, with capped collections offering a specialized fixed-size option. Next, you'll start actually inserting documents.

Next Lesson →

Inserting Documents