MongoDb - MongoDB, creating a database

In MongoDB, creating a database is a little different from relational databases like MySQL or PostgreSQL. You don’t explicitly “create” a database with a single command — instead, a database is created lazily the first time you store data in it.


1. Switch (or Create) a Database

In the MongoDB shell (mongosh), you use the use command:

use myDatabase
  • If myDatabase already exists → MongoDB switches to it.

  • If it doesn’t exist yet → MongoDB prepares it, but it won’t actually exist until you add a collection with documents.


2. Verify Current Database

Check which DB you’re currently using:

db

3. Create a Collection (and Trigger DB Creation)

To actually create the database, you need to create a collection and insert at least one document:

db.createCollection("users")
db.users.insertOne({ name: "Alice", age: 25 })

At this point:

  • The database myDatabase is created.

  • A collection users is created.

  • The document { name: "Alice", age: 25 } is stored.


4. Show Databases

Now, you can list all databases:

show dbs

Note: You’ll only see myDatabase in the list if it contains data. An empty DB won’t appear.


5. Drop (Delete) a Database

If you want to remove it:

db.dropDatabase()