Skip to content

๐Ÿง  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

{
  "_id": "672b9f3...",
  "name": "Yuvaraj",
  "age": 22,
  "skills": ["Node", "React", "AWS"]
}

โš™๏ธ 2. Basic Commands (Mongo Shell)

๐Ÿ‘‰ Show Databases

show dbs

๐Ÿ‘‰ Create / Use a Database

use myDB

๐Ÿ‘‰ Show Collections

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

db.users.deleteOne({ name: "Arun" })
db.users.deleteMany({ age: { $lt: 20 } })

๐Ÿงฉ 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.

{
  name: "Yuvaraj",
  address: { city: "Chennai", pincode: 600001 }
}

๐Ÿ‘‰ 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:

npm install mongoose

๐Ÿ‘‰ 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

await User.create({ name: "Yuvaraj", age: 22, city: "Chennai" });

Read

const users = await User.find({ age: { $gte: 20 } });
console.log(users);

Update

await User.updateOne({ name: "Yuvaraj" }, { $set: { city: "Bangalore" } });

Delete

await User.deleteOne({ name: "Yuvaraj" });

๐Ÿ”„ 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

userSchema.index({ name: 1 });

๐Ÿ“Š 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)

userSchema.pre("save", function(next) {
  console.log("Saving user:", this.name);
  next();
});

๐Ÿงฐ 15. Backup & Restore

# Backup
mongodump --db=myDB --out=backup/

# Restore
mongorestore --db=myDB backup/myDB

๐Ÿงพ 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()