MongoDB Basics
- What MongoDB is, differences between NoSQL and SQL databases, and MongoDB installation for backend development.
🔹 What is MongoDB?
MongoDB is a NoSQL, document-oriented database. Unlike traditional relational databases, MongoDB stores data in JSON-like documents (called BSON), making it flexible and scalable.
Key Features:
Stores data as documents, not tables
Schema-less: each document can have different fields
High performance for read/write operations
Easy horizontal scaling
Example Document in MongoDB:
Sample JSON Request Body
This JSON object represents a typical request body sent to an API. It includes user details such as name, email, age, and an array of skills, demonstrating how structured data can be sent from a client to a server for processing or storage.
{
"name": "Amit",
"email": "amit@gmail.com",
"age": 25,
"skills": ["JavaScript", "Node.js", "MongoDB"]
}
🔹 NoSQL vs SQL
Databases can be categorized into SQL (Relational) and NoSQL (Non-relational). MongoDB falls into the NoSQL category.
Example Comparison:
SQL Table:
| id | name | email |
|----|-------|----------------|
| 1 | Amit | amit@gmail.com |
- MongoDB Document:
{
"name": "Amit",
"email": "amit@gmail.com"
}
🔹 MongoDB Installation
MongoDB can be installed locally or accessed via cloud (MongoDB Atlas). After installation, developers can manage databases using Mongo Shell, Compass GUI, or Mongoose (Node.js).
Local Installation Steps
Download MongoDB Community Server from the official website
Install using default settings
Start the MongoDB service (mongod)
Verify installation:
mongo --version
MongoDB Atlas (Cloud)
Sign up at MongoDB Atlas
Create a free cluster
Connect your Node.js app using the connection string
Example Node.js Connection:
MongoDB Atlas (Cloud) Setup & Node.js Connection
Set up a MongoDB Atlas cloud cluster and connect your Node.js app using Mongoose. This allows remote database access and management without a local MongoDB installation.
const mongoose = require('mongoose');
mongoose.connect('mongodb+srv://<username>:<password>@cluster0.mongodb.net/myDB', {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => console.log('MongoDB connected'))
.catch(err => console.log(err));
MongoDB Compass (Local / GUI) Setup
Open MongoDB Compass.
Click “New Connection”.
Enter connection string (ya localhost URL, e.g., mongodb://127.0.0.1:27017).
Test connection → Connect.
Once connected, create your database & collections via Compass GUI.
Node.js Example (using Compass/Local MongoDB):
MongoDB Compass Setup & Node.js Connection
Set up MongoDB Compass to manage local databases and collections via GUI. Use Node.js with Mongoose to connect and perform database operations programmatically.
const mongoose = require('mongoose');
mongoose.connect('mongodb://127.0.0.1:27017/myDB', {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => console.log('MongoDB connected via Compass/local'))
.catch(err => console.log(err));