MongoDB Create Database

MongoDB has no CREATE DATABASE statement — databases are created lazily the first time you write data into one of their collections.

What Does "Create a Database" Mean in MongoDB?

In a relational engine you typically run an explicit CREATE DATABASE statement before anything else can happen. MongoDB takes a lazier approach: a database is simply a namespace, and it materializes automatically the moment you store the first document in one of its collections. Until that happens, the database exists only as a name you've switched to, with nothing persisted on disk.

The use Command

The use <database> command in mongosh sets your current working database for the session — every unqualified collection command afterward, such as db.orders.insertOne(...), targets that database. If the name you pass to use doesn't exist yet, mongosh happily switches to it anyway; it just won't show up anywhere until you actually write to it.

Relational WorkflowMongoDB Workflow
CREATE DATABASE shop;use shop
CREATE TABLE orders (...);no statement needed
INSERT INTO orders VALUES (...);db.orders.insertOne({...})
Database exists immediately after CREATEDatabase exists only after first write

Verifying Database Creation

  • Run use <name> to switch context
  • Insert at least one document into any collection
  • Run show dbs to confirm the database now appears
  • Run db.stats() to inspect storage size and collection counts
  • Run db.dropDatabase() to remove a database entirely

Switch to a database and insert

use analytics_app

db.events.insertOne({ type: "page_view", path: "/home" })
Note: If you run use analytics_app and immediately run show dbs without inserting anything, analytics_app will not appear in the list. Empty databases are not persisted.

Confirm with show dbs and stats

show dbs
db.stats()

Remove a database

use analytics_app
db.dropDatabase()
Note: Database names are case-sensitive and cannot contain spaces, the character '/', '\', '.', '"', or start with the reserved names admin, local, or config.

Exercise: MongoDB Create Database

What actually happens when you run 'use myNewDB' if myNewDB doesn't exist yet?