MongoDB Create Database

MongoDB Create Database

MongoDB Create Database

MongoDB does not have an explicit 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:

mongosh

B. Switch to the New Database

Even if the database doesn't exist yet, you can switch to it:

use blogDB

Expected Output:

switched to db blogDB

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:

db.posts.insertOne({ title: "Hello World", content: "This is my first post!" })

Expected Output:

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

Now, blogDB is permanently created.

D. Verify the Database Exists

Run:

show dbs

Expected Output:

admin 0.000GB config 0.000GB local 0.000GB blogDB 0.001GB

Now, blogDB appears in the list of databases.

2. Create a Database Using Node.js (Mongoose)

A. Install Mongoose (If Not Installed)

npm install mongoose

B. Create a Mongoose Schema

Create models/Post.js:

const mongoose = require('mongoose'); const postSchema = new mongoose.Schema({ title: { type: String, required: true }, content: { type: String, required: true }, createdAt: { type: Date, default: Date.now } }); const Post = mongoose.model("Post", postSchema); module.exports = Post;

C. Insert Data to Create the Database

Create createDatabase.js:

const mongoose = require('mongoose'); const Post = require('./models/Post'); mongoose.connect('mongodb://127.0.0.1:27017/blogDB', { useNewUrlParser: true, useUnifiedTopology: true }).then(() => console.log("✅ Connected to MongoDB")) .catch(err => console.error("❌ Connection Error:", err)); async function createDatabase() { try { const newPost = new Post({ title: "First Post", content: "This is my first blog post." }); await newPost.save(); console.log("✅ Database 'blogDB' created with initial document."); } catch (error) { console.log("❌ Error creating database:", error.message); } finally { mongoose.connection.close(); } } createDatabase();

D. Run the Script

node createDatabase.js

Expected Output:

✅ Connected to MongoDB ✅ Database 'blogDB' created with initial document.

3. Create a Database Using MongoDB Compass

If you prefer a graphical interface, follow these steps:

  1. Open MongoDB Compass and connect to your MongoDB server.
  2. Click "Create Database" at the top-left.
  3. Enter Database Name (e.g., blogDB).
  4. Enter Collection Name (e.g., posts).
  5. 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? 🚀

Souy Soeng

Souy Soeng

Our website teaches and reads PHP, Framework Laravel, and how to download Admin template sample source code free. Thank you for being so supportive!

Github

Post a Comment

CAN FEEDBACK
close