MongoDB Create Database
CREATE DATABASE
command. Instead, a database is automatically created when you insert the first document into a collection. This guide covers how to create a MongoDB database using MongoDB Shell, Node.js (Mongoose), and MongoDB Compass.1. Create a Database Using MongoDB Shell
A. Open MongoDB Shell
Start the MongoDB shell:
B. Switch to the New Database
Even if the database doesn't exist yet, you can switch to it:
✅ Expected Output:
At this point, blogDB
exists only in memory but is not saved on disk.
C. Create a Collection (Triggers Database Creation)
To persist the database, insert a document into a new collection:
✅ Expected Output:
Now, blogDB
is permanently created.
D. Verify the Database Exists
Run:
✅ Expected Output:
Now, blogDB
appears in the list of databases.
2. Create a Database Using Node.js (Mongoose)
A. Install Mongoose (If Not Installed)
B. Create a Mongoose Schema
Create models/Post.js
:
C. Insert Data to Create the Database
Create createDatabase.js
:
D. Run the Script
✅ Expected Output:
3. Create a Database Using MongoDB Compass
If you prefer a graphical interface, follow these steps:
- Open MongoDB Compass and connect to your MongoDB server.
- Click "Create Database" at the top-left.
- Enter Database Name (e.g.,
blogDB
). - Enter Collection Name (e.g.,
posts
). - Click "Create Database".
✅ The database is now created and visible in Compass.
4. Summary
✔ Created a database using MongoDB Shell (use database + insertOne()
).
✔ Used Mongoose to create a database programmatically.
✔ Created a database visually using MongoDB Compass.
5. Next Steps
🔹 Set up authentication for secure database access.
🔹 Optimize collections with indexes for better performance.
🔹 Monitor database storage and performance.
Would you like help setting up indexes or authentication? 🚀