๐ง 1. What is MongoDB?¶
-
NoSQL (document-oriented) database
-
Stores data as JSON-like documents (BSON format)
-
Very flexible โ no strict schema
-
Perfect for JavaScript/Node.js (data in same JSON format)
Example Document¶
โ๏ธ 2. Basic Commands (Mongo Shell)¶
๐ Show Databases¶
๐ Create / Use a Database¶
๐ Show Collections¶
๐๏ธ 3. CRUD Operations¶
โ Create¶
db.users.insertOne({ name: "Yuvaraj", age: 22, city: "Chennai" })
db.users.insertMany([
{ name: "Arun", age: 25 },
{ name: "Keerthi", age: 23 }
])
๐ Read¶
db.users.find() // all users
db.users.find({ age: 22 }) // filter
db.users.find({ age: { $gt: 20 } }) // condition
db.users.find({}, { name: 1 }) // projection (only name)
โ๏ธ Update¶
db.users.updateOne(
{ name: "Yuvaraj" },
{ $set: { city: "Bangalore" } }
)
db.users.updateMany(
{ age: { $gt: 21 } },
{ $inc: { age: 1 } }
)
โ Delete¶
๐งฉ 4. Query Operators¶
| Operator | Description | Example |
|---|---|---|
$gt, $lt, $gte, $lte |
Greater/Less than | { age: { $gt: 20 } } |
$in, $nin |
In/Not in | { city: { $in: ["Chennai","Delhi"] } } |
$or, $and |
Logical | { $or: [{ age: 22 }, { city: "Delhi" }] } |
$exists |
Check field presence | { city: { $exists: true } } |
$regex |
Pattern matching | { name: /yuva/i } |
๐ฆ 5. Indexing (for performance)¶
Indexes speed up queries by avoiding full collection scans.
db.users.createIndex({ name: 1 }) // ascending
db.users.createIndex({ age: -1 }) // descending
db.users.getIndexes()
โ Always index frequently searched or sorted fields.
๐งฎ 6. Aggregation Framework¶
Used for advanced data analysis and transformations.
๐ Basic Example¶
db.orders.aggregate([
{ $match: { status: "completed" } },
{ $group: { _id: "$customer", totalAmount: { $sum: "$amount" } } },
{ $sort: { totalAmount: -1 } }
])
๐ Common Aggregation Stages¶
| Stage | Purpose |
|---|---|
$match |
Filter documents |
$group |
Group data and aggregate |
$sort |
Sort results |
$project |
Include/rename fields |
$limit |
Limit number of docs |
$lookup |
Join with another collection |
๐ 7. Relationships (Referencing vs Embedding)¶
๐ Embedding (Nested documents)¶
Good for small, related data.
๐ Referencing (Using ObjectId)¶
Good for large or reusable data.
// users
{ _id: ObjectId("u1"), name: "Yuvaraj" }
// posts
{ title: "Hello", userId: ObjectId("u1") }
You can join them using $lookup:
db.posts.aggregate([
{
$lookup: {
from: "users",
localField: "userId",
foreignField: "_id",
as: "userDetails"
}
}
])
โ๏ธ 8. Using MongoDB with Node.js (Mongoose)¶
Install dependencies:
๐ Connect to MongoDB¶
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/mernDB")
.then(() => console.log("MongoDB Connected"))
.catch(err => console.log(err));
๐ Define Schema & Model¶
const userSchema = new mongoose.Schema({
name: String,
age: Number,
city: String
});
const User = mongoose.model("User", userSchema);
๐ CRUD in Mongoose¶
Create¶
Read¶
Update¶
Delete¶
๐ 9. Validation & Defaults (in Schema)¶
const productSchema = new mongoose.Schema({
name: { type: String, required: true },
price: { type: Number, min: 1 },
inStock: { type: Boolean, default: true }
});
๐ 10. Indexing in Mongoose¶
๐ 11. Pagination¶
const page = 2;
const limit = 5;
const users = await User.find()
.skip((page - 1) * limit)
.limit(limit);
๐ง 12. Aggregation in Mongoose¶
const result = await User.aggregate([
{ $group: { _id: "$city", count: { $sum: 1 } } }
]);
console.log(result);
๐พ 13. Relationships in Mongoose (Population)¶
๐ Referencing Example¶
const postSchema = new mongoose.Schema({
title: String,
user: { type: mongoose.Schema.Types.ObjectId, ref: "User" }
});
const Post = mongoose.model("Post", postSchema);
// Fetch posts with user details
const posts = await Post.find().populate("user");
๐ 14. Mongoose Middleware (Hooks)¶
๐งฐ 15. Backup & Restore¶
๐งพ 16. Best Practices¶
โ
Always use indexes on frequently queried fields
โ
Use Mongoose validation for data integrity
โ
Avoid large embedded arrays (>16MB limit)
โ
Use .lean() for read-only queries (improves performance)
โ
Use $lookup or .populate() for relations
โ
Monitor with MongoDB Compass or Atlas
๐บ๏ธ Quick Summary¶
| Concept | Command / Example |
|---|---|
| Create | insertOne() |
| Read | find() |
| Update | updateOne() |
| Delete | deleteOne() |
| Query | $gt, $in, $or, $regex |
| Aggregation | $match, $group, $sort, $lookup |
| Index | createIndex() |
| Relationship | $lookup, .populate() |
| Validation | { type, required, default } |
| Pagination | .skip().limit() |