Skip to content
FullStackDost Logo
  • All Courses
  • Blogs
  • Login
  • Register
  • All Courses
  • Blogs
  • Login
  • Register
  • Home
  • All Courses
  • Web development
  • MongoDB – (No-SQL)

MongoDB – (No-SQL)

Curriculum

  • 10 Sections
  • 31 Lessons
  • 10 Weeks
Expand all sectionsCollapse all sections
  • Introduction to MongoDB
    MongoDB is a NoSQL database that is designed for handling large volumes of unstructured or semi-structured data. Unlike traditional relational databases (RDBMS) that use tables and rows to organize data, MongoDB stores data in a flexible document-oriented format using JSON-like documents (BSON - Binary JSON). This makes it highly scalable, flexible, and performant for applications that need to handle varying types of data with complex structures.
    5
    • 1.1
      What is MongoDB?
    • 1.2
      Why MongoDB?
    • 1.3
      When to use MongoDB?
    • 1.4
      Key Features of MongoDB
    • 1.5
      Installing MongoDB
  • MongoDB Basic Operations
    MongoDB provides a rich set of basic operations for interacting with the database, including creating, reading, updating, and deleting data (often abbreviated as CRUD operations). Below are the basic operations that you can perform with MongoDB.
    2
    • 2.0
      Database and Collection Basics
    • 2.1
      CRUD Operations
  • Advanced Querying Techniques
    MongoDB offers a rich set of querying capabilities, and as you work with larger datasets and more complex application requirements, you’ll often need to use advanced querying techniques. These techniques help you optimize performance, execute sophisticated queries, and leverage MongoDB’s powerful indexing and aggregation features.
    4
    • 3.1
      Query Filters and Operators
    • 3.2
      Advanced Querying
    • 3.3
      Sorting and Limiting Results
    • 3.4
      Aggregation Framework
  • Data Modeling and Schema Design
    Data modeling and schema design are critical when using MongoDB (or any NoSQL database) to ensure efficient data storage, fast queries, and scalability. Unlike relational databases, MongoDB is schema-less, which means you are not required to define a fixed schema upfront. However, making the right design decisions from the beginning is essential for maintaining performance and avoid complications as your data grows.
    4
    • 4.1
      Data Modeling
    • 4.2
      Document Structure
    • 4.3
      Schema Design Patterns
    • 4.4
      MongoDB and Relationships
  • Indexing and Performance Optimization
    In MongoDB, indexing is a critical part of performance optimization. Without proper indexes, MongoDB has to scan every document in a collection to satisfy queries, which can be very inefficient for large datasets. Indexes are used to quickly locate data without scanning every document, making reads faster and more efficient.
    3
    • 5.0
      Creating Indexes
    • 5.1
      Using Text Search
    • 5.2
      Performance Optimization
  • Integrating MongoDB with a Web Application (Node.js)
    Integrating MongoDB with a web application built using Node.js is a common and powerful combination for building scalable and efficient web apps. MongoDB’s flexibility with JSON-like data and Node.js's asynchronous event-driven architecture work well together. In this guide, I'll walk you through the steps for integrating MongoDB with a Node.js web application, covering the essentials of setting up the connection, performing CRUD operations, and using popular libraries.
    3
    • 6.0
      Setting Up MongoDB with Node.js
    • 6.1
      CRUD Operations with Mongoose
    • 6.2
      Error Handling and Validation
  • Security in MongoDB
    Security is an essential aspect when working with MongoDB, especially when handling sensitive data in production environments. MongoDB provides a variety of security features to help protect your data against unauthorized access, injection attacks, and other vulnerabilities. Here’s a guide on securing MongoDB and your Node.js application when interacting with MongoDB.
    2
    • 7.0
      Authentication and Authorization
    • 7.1
      Data Encryption
  • Working with MongoDB in Production
    3
    • 8.0
      MongoDB Backup and Restore
    • 8.1
      MongoDB Scaling and Sharding
    • 8.2
      MongoDB Replication
  • Deploying and Monitoring MongoDB
    Working with MongoDB in a production environment requires careful planning, attention to detail, and best practices to ensure optimal performance, security, reliability, and scalability.
    3
    • 9.0
      Deploying MongoDB to Production
    • 9.1
      Monitoring and Management
    • 9.2
      Summary for MongoDB deployment on Production
  • Building a Web App with MongoDB (Final Project)
    Demo Project (OneStopShop)
    2
    • 10.0
      Building the Application
    • 10.1
      Final Project Features

Creating Indexes

Creating indexes in MongoDB is crucial for improving query performance, especially as your dataset grows. Indexes help MongoDB quickly locate and access the required data without scanning the entire collection, making read operations more efficient. In this section, we’ll walk through how to create different types of indexes in MongoDB, how to manage them, and best practices for creating and using indexes effectively.

1. Creating Single-Field Indexes

A single-field index is an index on one field of a document. It’s the most basic type of index and speeds up queries that filter or sort by a specific field.

Syntax:

javascript

Copy code

db.collection.createIndex({ fieldName: 1 }) // Ascending index (1) db.collection.createIndex({ fieldName: -1 }) // Descending index (-1)

  • Ascending Index (1): Sorts the field in ascending order.
  • Descending Index (-1): Sorts the field in descending order.

Example:

Creating an index on the name field in ascending order:

javascript

Copy code

db.users.createIndex({ name: 1 })

Use case:

This index will speed up queries that filter or sort by name, for example:

javascript

Copy code

db.users.find({ name: "Alice" })

2. Creating Compound Indexes

A compound index is an index on multiple fields. Compound indexes are used when your queries filter on multiple fields, and they can optimize queries that use any of the fields in the index.

Syntax:

javascript

Copy code

db.collection.createIndex({ field1: 1, field2: -1 })

The order of fields in a compound index is important. MongoDB uses the index to efficiently filter or sort based on the left-most field in the index.

Example:

Creating a compound index on firstName (ascending) and lastName (descending):

javascript

Copy code

db.users.createIndex({ firstName: 1, lastName: -1 })

Use case:

This index will speed up queries like:

javascript

Copy code

db.users.find({ firstName: "John", lastName: "Doe" }) db.users.find({ firstName: "John" }).sort({ lastName: -1 })

3. Creating Multikey Indexes

A multikey index is used when a field contains an array. MongoDB creates a separate index entry for each element of the array, allowing for efficient querying of documents with arrays.

Syntax:

javascript

Copy code

db.collection.createIndex({ fieldName: 1 })

If the fieldName is an array, MongoDB will automatically create a multikey index.

Example:

Creating a multikey index on a tags array field:

javascript

Copy code

db.posts.createIndex({ tags: 1 })

Use case:

This index will speed up queries like:

javascript

Copy code

db.posts.find({ tags: "mongodb" })

4. Creating Text Indexes

A text index allows for text search on string fields. MongoDB supports full-text search, which includes word stemming, tokenization, and case-insensitive searches.

Syntax:

javascript

Copy code

db.collection.createIndex({ fieldName: "text" })

You can create a text index on one or more fields. MongoDB automatically indexes all string fields as part of the text index.

Example:

Creating a text index on the description field:

javascript

Copy code

db.products.createIndex({ description: "text" })

Use case:

This index will support text search queries:

javascript

Copy code

db.products.find({ $text: { $search: "laptop" } })

You can also use the $text operator to find documents with text that matches specific words or phrases.

5. Creating Hashed Indexes

A hashed index is used for sharding or for equality queries that require fast lookups by hash value.

Syntax:

javascript

Copy code

db.collection.createIndex({ fieldName: "hashed" })

Example:

Creating a hashed index on the userId field:

javascript

Copy code

db.users.createIndex({ userId: "hashed" })

Use case:

Hashed indexes are typically used in sharded collections where the shard key is hashed to distribute data across different shards.

6. Creating Geospatial Indexes

MongoDB supports geospatial queries. A geospatial index allows you to index geographical data, such as coordinates, to perform location-based queries (e.g., finding documents near a given point).

Types of Geospatial Indexes:

  • 2d Index: For flat (Cartesian) coordinate systems (deprecated in newer versions).
  • 2dsphere Index: For spherical (geo-coordinates) systems, supporting queries that work with Earth’s spherical geometry.

Syntax for 2dsphere index:

javascript

Copy code

db.collection.createIndex({ location: "2dsphere" })

Example:

Creating a 2dsphere index on a location field to store geographic coordinates:

javascript

Copy code

db.places.createIndex({ location: "2dsphere" })

Use case:

This index enables queries like:

javascript

Copy code

db.places.find({ location: { $nearSphere: { $geometry: { type: "Point", coordinates: [ -73.9667, 40.78 ] }, $maxDistance: 1000 } } })

7. Creating TTL (Time-to-Live) Indexes

A TTL index automatically removes documents from the collection after a specified period of time. This is useful for managing documents with an expiration time (e.g., session data, logs).

Syntax:

javascript

Copy code

db.collection.createIndex({ fieldName: 1 }, { expireAfterSeconds: <seconds> })

Example:

Creating a TTL index on a createdAt field to expire documents after 3600 seconds (1 hour):

javascript

Copy code

db.sessions.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 })

Use case:

This index automatically removes expired session documents after one hour, keeping your data fresh without manual intervention.

8. Creating Wildcard Indexes

A wildcard index allows you to index all fields within a document, which is useful when the document structure is dynamic and fields are added/removed over time.

Syntax:

javascript

Copy code

db.collection.createIndex({ "$**": 1 })

Example:

Creating a wildcard index on all fields in a document:

javascript

Copy code

db.users.createIndex({ "$**": 1 })

Use case:

This type of index is useful when your documents have dynamic structures, and you want to search any field in the document.

9. Managing Indexes

9.1 Listing Indexes

You can list all indexes in a collection using the getIndexes() method.

javascript

Copy code

db.collection.getIndexes()

9.2 Dropping Indexes

To drop an index, use the dropIndex() method. You can specify the index by its name or its index specification.

javascript

Copy code

db.collection.dropIndex("indexName") // Drop by name db.collection.dropIndex({ fieldName: 1 }) // Drop by field

9.3 Dropping All Indexes

To drop all indexes (except the default _id index), use dropIndexes():

javascript

Copy code

db.collection.dropIndexes()

10. Indexing Considerations

  • Index Creation and Write Performance: While indexes can significantly improve read performance, they come at the cost of slower write operations (inserts, updates, deletes). Each time a document is modified, MongoDB must also update the indexes.
  • Disk Space: Indexes consume additional disk space. For large collections, managing indexes efficiently can help reduce unnecessary storage overhead.
  • Selective Indexing: It’s important to only create indexes on fields that are frequently queried. Over-indexing can slow down writes and waste resources.
  • Use explain() to Analyze Queries: Use the explain() method to analyze your queries and ensure that the indexes are being used effectively.javascriptCopy codedb.collection.find({ fieldName: "value" }).explain("executionStats")

Conclusion

Indexes are essential for optimizing query performance in MongoDB, especially as data grows. Understanding which types of indexes to use and when to use them can help ensure that your application remains responsive as your dataset scales. Always test and monitor your indexes using tools like explain() to make sure you’re getting the best performance from your MongoDB queries.

MongoDB and Relationships
Prev
Using Text Search
Next

Copyright © 2025 FullStackDost. All Rights Reserved.

Theme by ILOVEWP