Skip to content

Advanced Concepts

Basics seekhne ke baad, ab baari hai kuch advanced concepts ki jo MongoDB ko real-time applications ke liye powerful banate hain.


1. Indexing (Speed Up Queries)

Jab database me lakhon documents hote hain, to query slow ho sakti hai. Indexing se hum searches ko fast banate hain.

  • Create Index: db.users.createIndex({ name: 1 }) (1 matlab ascending order).
  • View Indexes: db.users.getIndexes().
  • Drop Index: db.users.dropIndex("name_1").
Pro tip: Indexing se read fast hota hai par write thoda slow, isliye sirf zaroori fields par hi index banayein! ⚡

2. Aggregation Framework

Aggregation ka matlab hai data ko process karke results nikalna (jaise Average, Sum, ya Grouping). Ye ek pipeline ki tarah kaam karta hai.

Common Stages:

  • $match: Documents filter karne ke liye.
  • $group: Data ko group karne ke liye.
  • $sort: Sorting ke liye.
  • $limit: Results restrict karne ke liye.

Example: City wise users count

db.users.aggregate([
{ $match: { age: { $gte: 18 } } }, // Pehle filter karo
{ $group: { _id: "$city", totalUsers: { $sum: 1 } } } // Phir group karo
]);

3. Capped Collections

Ye fixed-size collections hoti hain. Jab limit finish ho jati hai, to naye documents purane wale ko overwrite kar dete hain. (Logging ke liye best hain).

db.createCollection("logs", { capped: true, size: 5242880, max: 5000 });

4. Security Basics

Production me database security bahut zaroori hai.

  • Authentication: mongod --auth se restart karein.
  • Role-Based Access: readWrite, dbAdmin, ya root roles assign karein.
  • Encryption: At-rest aur In-transit dono security apply karein.

5. Connection Pooling (Performance Booster)

Har request ke liye bar-bar database connect karna slow hota hai. Connection Pooling ka matlab hai ki hum ek baar connection open karte hain aur usse reuse karte hain.

  • Kyun chahiye?: Har naya connection banane me “Handshake” hota hai jo time leta hai. Pool se bana-banaya connection mil jata hai.
  • Node.js/Mongoose Example: Default poolSize 5 hota hai, par aap production me isse badha sakte hain:
    mongoose.connect(uri, {
    maxPoolSize: 10, // Ek saath 10 connections open rahenge
    minPoolSize: 2 // Kam se kam 2 hamesha ready rahenge
    });

Next Steps

Ab aapne MongoDB ke kaafi concepts seekh liye hain! Inhe practice karne ke liye MongoDB Compass ya Atlas (Cloud) ka use karein.

Happy Coding! 🚩