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.
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" })Confirm with show dbs and stats
show dbs
db.stats()Remove a database
use analytics_app
db.dropDatabase()Exercise: MongoDB Create Database
What actually happens when you run 'use myNewDB' if myNewDB doesn't exist yet?