MongoDB Create Database

MongoDB does not explicitly create a database until it contains some data. Unlike traditional relational databases where you must explicitly create a database, MongoDB creates a database dynamically when you insert the first document into a collection.

Key Points About MongoDB Databases

  1. Dynamic Database Creation: MongoDB creates a database only when a collection with data is inserted.
  2. No Predefined Schema: MongoDB databases are schema-less, allowing flexible structures for documents.
  3. Default Databases: MongoDB includes three default databases: admin, local and config.

Prerequisites

  1. MongoDB Installed: Download MongoDB from mongodb.com.
  2. Node.js Installed: Download and install Node.js from nodejs.org.
  3. MongoDB Shell or Compass: Use the MongoDB shell (CLI) or MongoDB Compass (GUI) for database management.

Method 1: Create Database Using MongoDB Shell

Step 1: Open the MongoDB Shell

Open your terminal or command prompt.

Run the command:

mongosh

Step 2: Switch to a Database

To create or switch to a database, use the use command:

use myDatabase

If the database myDatabase does not exist, MongoDB will create it when you insert the first document.

You’ll see the message:

switched to db myDatabase

Step 3: Insert Data

Insert a document to create the database:

db.users.insertOne({ name: 'Alice', age: 25 });
  • users: Name of the collection.
  • Document: A record in the collection.

Verify the Database

List all databases:

show dbs

Method 2: Create Database Using Node.js

Step 1: Install MongoDB Driver

Run the following command to install the MongoDB Node.js driver:

npm install mongodb

Step 2: Connect to MongoDB

Create a file named app.js and write the following code:

const { MongoClient } = require('mongodb');

// Connection URL
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);

// Database Name
const dbName = 'myDatabase';

async function main() {
try {
// Connect to MongoDB
await client.connect();
console.log('Connected successfully to MongoDB');

// Create or use the database
const db = client.db(dbName);

// Insert a document into a collection
const result = await db.collection('users').insertOne({ name: 'Bob', age: 30 });
console.log('Document inserted with ID:', result.insertedId);
} catch (err) {
console.error('Error:', err);
} finally {
// Close the connection
await client.close();
}
}

main();

Explanation:

  • MongoClient: Used to connect to the MongoDB server.
  • db.collection(‘users’): Creates or selects the users collection.
  • insertOne: Inserts a document into the collection, creating the database if it doesn’t exist.

Method 3: Create Database Using MongoDB Compass

MongoDB Compass is a GUI tool that simplifies database management.

Step 1: Open MongoDB Compass

  1. Open the Compass application.
  2. Connect to your MongoDB server (default is mongodb://localhost:27017).

Step 2: Create a New Database

  1. Click the “Create Database” button.
  2. Enter the database name (myDatabase).
  3. Enter the collection name (users).
  4. Click “Create Database” to create both the database and the collection.

Verifying the Database

MongoDB Shell:

Use the following commands:

Switch to the database:

use myDatabase

List collections:

show collections

View data:

db.users.find()

Node.js:

Modify the app.js file to retrieve and display data:

const users = await db.collection('users').find().toArray();
console.log('Users:', users);

Real-World Use Case

Imagine building a user management system. Here’s how you can create a database and add users dynamically:

Example: User Management

async function addUser(name, age) {
const db = client.db('userManagement');
const result = await db.collection('users').insertOne({ name, age });
console.log('User added with ID:', result.insertedId);
}

// Example usage
await addUser('John', 28);
await addUser('Emma', 35);

Leave a Comment

BoxofLearn