All academies
Roadmap
LEVEL 2 · INSTALLATION & SETUP

Databases & Collections

7 min read

MongoDB creates databases and collections lazily: use blog switches to a database that may not exist yet, and the first insert actually creates it.

mongosh
use blog                     // switch (nothing created yet)
db.posts.insertOne({ title: "Hello" })  // creates db + collection
show dbs                     // now 'blog' appears
show collections

Explicit creation

Use db.createCollection() when you need options like validation rules or capped collections:

mongosh
db.createCollection("logs", {
  capped: true, size: 1048576, max: 1000
})

Dropping things

db.collection.drop() removes a collection and its indexes. db.dropDatabase() removes the current database. Both are irreversible — there is no undo.

Try it yourself

use blog
Run in Shell

Check your understanding

Q1.

You run `use inventory` on a fresh server, then `show dbs`. Does 'inventory' appear?

code
use inventory
show dbs
Q2.

db.dropDatabase() drops the database you are currently using.