MongoDB mongosh Create Database

MongoDB Tutorial

MongoDB mongosh Create Database

In MongoDB mongosh Create Database are created automatically when you store data in them.
There is no CREATE DATABASE command like in SQL.


1️⃣ Start mongosh

Open Terminal / Command Prompt and run:

mongosh

You’ll see a prompt like:

test>

2️⃣ Check Existing Databases

show dbs

 Example output:

admin 40.00 KiB
local 72.00 KiB
config 60.00 KiB

3️⃣ Switch to (Create) a New Database

Use the use command:

use myDatabase

Output:

switched to db myDatabase

Important:
At this stage, the database is NOT actually created yet.


4️⃣ Create Database by Inserting Data

MongoDB creates a database only when data is inserted.

Example: Create a collection and insert a document


 

Output:

{
acknowledged: true,
insertedId: ObjectId("...")
}

 Now the database is officially created.


5️⃣ Verify Database Creation

show dbs

Now you’ll see:

myDatabase 8.00 KiB

6️⃣ Check Current Database

db

Output:

myDatabase

7️⃣ Create Multiple Collections (Optional)


 

MongoDB automatically creates:

  • products collection

  • orders collection


8️⃣ Create Empty Collection (Optional)

If you want a collection without inserting data:

db.createCollection("employees")

Output:

{ ok: 1 }

9️⃣ Delete a Database (Extra – Interview Tip)

db.dropDatabase()

 Deletes the current database completely.


Key Points (Very Important for Exams & Interviews)

✔ MongoDB creates databases automatically
use dbName → switches database context
✔ Database appears only after data insertion
✔ Collections are creating automatically
✔ No CREATE DATABASE command in MongoDB


 Common Interview Questions

Q1. Does use myDB create a database?
👉 ❌ No, it only switches context

Q2. When is a database actually creating?
👉 ✅ When the first document is inserting

Q3. Can MongoDB have empty databases?
👉 ❌ No, it must contain data


Summary


 That’s all you need to create a database in MongoDB using mongosh.

You may also like...