MongoDB Basics
Learn the fundamentals of NoSQL with MongoDB
1. Introduction to MongoDB
What is MongoDB?
MongoDB is a popular NoSQL database that stores data in flexible, JSON-like documents. It's designed for scalability and performance with features like horizontal scaling and rich queries.
Features of MongoDB
- Document-oriented storage (BSON format)
- Full index support
- Replication and high availability
- Auto-sharding for horizontal scaling
- Rich query language
SQL vs NoSQL
| SQL Databases | MongoDB (NoSQL) |
|---|---|
| Tables with fixed schema | Collections with dynamic schema |
| Rows | Documents |
| Columns | Fields |
| JOIN operations | Embedded documents or references |
2. MongoDB Installation & Setup
Installation
Download MongoDB Community Server from official website and follow installation wizard for your OS.
MongoDB Compass
GUI tool for MongoDB with schema visualization, query building, and performance analysis.
MongoDB Shell
Interactive JavaScript interface (mongosh) for querying and administration.
# Start MongoDB service (Linux) sudo systemctl start mongod # Connect to MongoDB shell mongosh # Check service status sudo systemctl status mongod
3. MongoDB Database Basics
// Create/switch to a database (created when first document is inserted) use mydb // List all databases show dbs // Current database db // Drop a database db.dropDatabase()
4. Collections and Documents
Document Structure
{
"_id": ObjectId("5f8d..."),
"name": "John Doe",
"age": 30,
"address": {
"street": "123 Main St",
"city": "New York"
},
"hobbies": ["reading", "hiking"]
}
Inserting Documents
// Insert single document
db.users.insertOne({
name: "Alice",
age: 25,
status: "active"
})
// Insert multiple documents
db.users.insertMany([
{name: "Bob", age: 30},
{name: "Charlie", age: 35}
])
Viewing Documents
// Find all documents db.users.find() // Pretty print results db.users.find().pretty()
5. Querying in MongoDB
Basic Queries
// Find all documents
db.users.find()
// Find with projection (select fields)
db.users.find({}, {name: 1, age: 1})
// Find one document
db.users.findOne({age: {$gt: 25}})
Comparison Operators
// $eq, $ne, $gt, $lt, $gte, $lte, $in
db.users.find({age: {$gt: 25}})
db.users.find({status: {$in: ["active", "pending"]}})
Logical Operators
// $and, $or, $not
db.users.find({
$and: [
{age: {$gt: 25}},
{status: "active"}
]
})
db.users.find({
$or: [
{status: "active"},
{status: "pending"}
]
})
Querying Embedded Documents
// Query nested fields
db.users.find({"address.city": "New York"})
// Query array elements
db.users.find({hobbies: "reading"})
6. CRUD Operations
Insert
// Insert single
db.users.insertOne({
name: "David",
age: 40
})
// Insert multiple
db.users.insertMany([
{name: "Eve", age: 28},
{name: "Frank", age: 32}
])
Update
// Update one document
db.users.updateOne(
{name: "Alice"},
{$set: {age: 26}}
)
// Update many documents
db.users.updateMany(
{status: "active"},
{$inc: {score: 5}}
)
Delete
// Delete one document
db.users.deleteOne({name: "Bob"})
// Delete many documents
db.users.deleteMany({status: "inactive"})
7. MongoDB Data Types
Basic Types
String- UTF-8 textNumber- Integer (32/64-bit) or DoubleBoolean- true/falseDate- TimestampNull- Null value
Complex Types
Array- Ordered list of valuesObject- Embedded documentObjectId- Unique identifier (12-byte)Binary data- For storing binary
Example Document
{
_id: ObjectId("..."),
name: "John",
age: 30,
active: true,
joined: ISODate("2023-01-15"),
address: {
city: "New York"
},
tags: ["staff", "admin"]
}
8. Indexes in MongoDB
Why Indexes?
Indexes support efficient query execution by organizing data to minimize the number of documents MongoDB needs to scan.
Creating Indexes
// Single field index
db.users.createIndex({name: 1}) // 1 for ascending
// Compound index
db.users.createIndex({name: 1, age: -1})
// Text index for search
db.articles.createIndex({content: "text"})
Index Types
- Single Field - On a single field
- Compound - On multiple fields
- Multikey - For array fields
- Text - For text search
- Geospatial - For location data
Viewing Indexes
// List all indexes db.users.getIndexes() // Get index size db.users.totalIndexSize()
9. Aggregation Framework
What is Aggregation?
The aggregation framework processes data records and returns computed results through a pipeline of operations.
Basic Pipeline Stages
// Simple aggregation
db.orders.aggregate([
{ $match: { status: "completed" } },
{ $group: {
_id: "$customer",
total: { $sum: "$amount" }
}
},
{ $sort: { total: -1 } }
])
Common Stages
$match- Filter documents$group- Group by expression$sort- Sort documents$project- Reshape documents$limit- Limit number of documents$skip- Skip documents$unwind- Deconstruct array
Aggregation Operators
$sum,$avg,$min,$max$push,$addToSet$first,$last
10. MongoDB Security Basics
Role-Based Access Control
// Create user with roles
db.createUser({
user: "admin",
pwd: "password123",
roles: ["readWrite", "dbAdmin"]
})
// Create custom role
db.createRole({
role: "readOnly",
privileges: [
{ resource: { db: "mydb", collection: "" },
actions: ["find"] }
],
roles: []
})
Security Practices
- Enable authentication in mongod.conf
- Use strong passwords
- Limit network exposure
- Implement TLS/SSL encryption
- Regularly update MongoDB
Network Access Control
# In mongod.conf net: bindIp: 127.0.0.1 # Only local connections port: 27017 security: authorization: enabled
11. MongoDB and Programming Languages
Node.js (Mongoose)
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/mydb');
const userSchema = new mongoose.Schema({
name: String,
age: Number
});
const User = mongoose.model('User', userSchema);
Python (PyMongo)
from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client.mydb
# Insert document
db.users.insert_one({
'name': 'Alice',
'age': 25
})
Java
MongoClient client = new MongoClient();
MongoDatabase db = client.getDatabase("mydb");
// Find documents
MongoCollection users = db.getCollection("users");
FindIterable result = users.find();
12. MongoDB Atlas (Cloud MongoDB)
What is Atlas?
MongoDB Atlas is a fully-managed cloud database service that handles deployment, scaling, and management of MongoDB.
Key Features
- Automated provisioning and scaling
- Backups and point-in-time recovery
- Performance optimization
- Security features
- Global clusters
Getting Started
- Sign up for free tier at mongodb.com/atlas
- Create a cluster (M0 free tier available)
- Set up network access and database user
- Connect using connection string
Connection String
mongodb+srv://username:password@cluster0.mongodb.net/mydb
13. Backup & Restore
mongodump/mongorestore
# Backup a database mongodump --db mydb --out /backup/ # Restore a database mongorestore --db mydb /backup/mydb/
mongoexport/mongoimport
# Export to JSON mongoexport --db mydb --collection users --out users.json # Export to CSV mongoexport --db mydb --collection users --type=csv --fields name,age --out users.csv # Import from JSON mongoimport --db mydb --collection users --file users.json
14. Common Tools
MongoDB Compass
Official GUI with schema visualization, CRUD operations, and performance metrics.
Robo 3T
Lightweight GUI with shell integration and query autocompletion.
NoSQLBooster
Feature-rich GUI with SQL query support and visual query builder.