MongoDB mongosh Create Database

MongoDB mongosh – Create Database 🗄️

In MongoDB, databases are created dynamically.

👉 You don’t explicitly create a database — it is created automatically when you insert data into it.


Step 1️⃣ Open mongosh

Open terminal / command prompt and run:

mongosh

If connected successfully, you’ll see:

test>

Step 2️⃣ Check Existing Databases

show dbs

📌 The database you create will not appear here until it contains data.


Step 3️⃣ Create (Switch to) a New Database

Use the use command:

use collegeDB

Output:

switched to db collegeDB

⚠️ At this stage, the database is not yet created physically.


Step 4️⃣ Insert Data (This Creates the Database)

Insert a document into a collection:

db.students.insertOne({
name: "Amit",
age: 21,
course: "BA"
})

Output:

acknowledged: true
insertedId: ObjectId("...")

Now the database is created


Step 5️⃣ Verify Database Creation

show dbs

You’ll now see:

collegeDB

Step 6️⃣ View Collections

show collections

Output:

students

Step 7️⃣ View Data

db.students.find().pretty()

Important Notes ⚠️

  • MongoDB creates databases only after data insertion

  • Empty databases are not stored

  • Database names are case-sensitive

  • Avoid special characters in database names


Quick Summary 📝

mongosh // open shell
use collegeDB // select database
db.students.insertOne() // creates DB + collection
show dbs // verify database

You may also like...