Performance

  • Performance optimization improves application speed using MongoDB indexing and efficient API design techniques.
  • 🔹 Indexing in MongoDB

    What is Indexing?

    Indexing in MongoDB is a technique used to speed up data retrieval.
    An index works like a book index — instead of scanning every page, MongoDB directly jumps to the required records.

    Without indexing, MongoDB performs a collection scan, which becomes slow as data grows.


    Why Indexing Matters

    • Faster query execution

    • Reduced CPU & disk usage

    • Improves API response time

    • Essential for large datasets

    Example – Query Without Index

Indexing in MongoDB

Indexing improves query performance by allowing MongoDB to quickly locate data instead of scanning the entire collection, which is essential for large datasets.

Product.find({ category: "electronics" });
  • MongoDB checks every document in the collection.

    Creating an Index

db.products.createIndex({ category: 1 });
  • Now MongoDB can find matching documents directly.

    Index in Mongoose

const productSchema = new mongoose.Schema({
  name: String,
  category: String,
  price: Number
});

productSchema.index({ category: 1 });
  • Common Index Types
    • Single Field Index{ email: 1 }

    • Compound Index{ category: 1, price: 1 }

    • Unique Index{ email: 1 } (no duplicates)

    • Text Index → Used for search

    🔹 API Optimization

    What is API Optimization?

    API Optimization focuses on making APIs faster, lighter, and more efficient by reducing unnecessary work on the server and database.


    Key Optimization Techniques

    1. Return Only Required Data

Product.find({}, { name: 1, price: 1 });
  • Avoids sending unnecessary fields.

    2. Pagination Instead of Full Data

Product.find()
  .skip((page - 1) * limit)
  .limit(limit);
  • Prevents loading large datasets at once.

    3. Use Index-Friendly Queries

    • Avoid filtering on non-indexed fields

    • Index fields used in:

      • filtering

      • sorting

      • searching


    🔹 4. Avoid Blocking Operations

    Use async/await and non-blocking I/O:

const products = await Product.find(filter);