Skip to main content

Command Palette

Search for a command to run...

MongoDB

Published
โ€ข22 min readโ€ขView as Markdown
N

Hi, Iโ€™m Neetesh Lodhi, a passionate Backend Developer and a 7th-semester CSE B.Tech student. I love building scalable web applications, crafting clean APIs, and solving real-world problems through technology. My core expertise lies in Node.js, Express.js, and MongoDB, Java and Iโ€™m currently exploring DevOps, Docker, and System Design to strengthen my backend foundation.

What is mongoDB?

MongoDB is a popular NoSQL database that is designed to store and manage large volumes of structured and unstructured data. Unlike traditional relational databases, which use a fixed schema and tables to store data, MongoDB uses a flexible document model to store data in collections. This allows for a more dynamic and scalable approach to data management, as data can be added and modified without the need to first define a schema.

MongoDB is known for its high performance and scalability, as it is able to handle large amounts of data and high traffic loads with ease. It is also highly flexible and can be used in a wide range of applications, from web and mobile apps to data analytics and real-time processing.

MongoDB is open source software, which means that it is free to use and can be customized and modified by developers to fit their specific needs. It is widely used by organizations of all sizes, from small startups to large enterprises, and is supported by a large community of developers and users.

MongoDB Features

1โ€ขEach database contains collections which in turn contains documents. Each document can be different with a varying number of fields. The size and content of each document can be different from each other.
2โ€ขThe document structure is more in line with how developers construct their classes and objects in their respective programming languages. Developers will often say that their classes are not rows and columns but have a clear structure with key-value pairs.
3โ€ขThe rows (or documents as called in MongoDB) doesnโ€™t need to have a schema defined beforehand. Instead, the fields can be created on the fly.
4โ€ขThe data model available within MongoDB allows you to represent hierarchical relationships, to store arrays, and other more complex structures more easily.
5โ€ขScalability โ€“ The MongoDB environments are very scalable. Companies across the world have defined clusters with some of them running 100+ nodes with around millions of documents within the database.

MongoDB Example

Press enter or click to view image in full size

1.The _id field is added by MongoDB to uniquely identify the document in the collection.

2.What you can note is that the Order Data (OrderID, Product, and Quantity ) which in RDBMS will normally be stored in a separate table, while in MongoDB it is actually stored as an embedded document in the collection itself. This is one of the key differences in how data is modeled in MongoDB.

Press enter or click to view image in full size

Key Components of MongoDB Architecture

๐Ÿ”นBelow are a few of the common terms used in MongoDB

๐Ÿ”น_id โ€“ This is a field required in every MongoDB document. The id field represents a unique value in the MongoDB document. The id field is like the documentโ€™s primary key. If you create a new document without an _id field, MongoDB will automatically create the field. So for example, if we see the example of the above customer table, Mongo DB will add a 24 digit unique identifier to each document in the collection.

Press enter or click to view image in full size

๐Ÿ”นCollection โ€“ This is a grouping of MongoDB documents. A collection is the equivalent of a table which is created in any other RDMS such as Oracle or MS SQL. A collection exists within a single database. As seen from the introduction collections donโ€™t enforce any sort of structure.
๐Ÿ”นCursor โ€“ This is a pointer to the result set of a query. Clients can iterate through a cursor to retrieve results.
๐Ÿ”นDatabase โ€“ This is a container for collections like in RDMS wherein it is a container for tables. Each database gets its own set of files on the file system. A MongoDB server can store multiple databases.
๐Ÿ”นDocument โ€“ A record in a MongoDB collection is basically called a document. The document, in turn, will consist of field name and values.
๐Ÿ”นField โ€“ A name-value pair in a document. A document has zero or more fields. Fields are analogous to columns in relational databases.The following diagram shows an example of Fields with Key value pairs. So in the example below CustomerID and 11 is one of the key value pairโ€™s defined in the document.

Press enter or click to view image in full size

๐Ÿ”นJSON โ€“ This is known as JavaScript Object Notation. This is a human-readable, plain text format for expressing structured data. JSON is currently supported in many programming languages.

๐Ÿ”ธJust a quick note on the key difference between the id field and a normal collection field. The id field is used to uniquely identify the documents in a collection and is automatically added by MongoDB when the collection is created.

Why Use MongoDB?

Below are the few of the reasons as to why one should start using MongoDB

๐ŸŸขDocument-oriented โ€“ Since MongoDB is a NoSQL type database, instead of having data in a relational type format, it stores the data in documents. This makes MongoDB very flexible and adaptable to real business world situation and requirements.
๐ŸŸขAd hoc queries โ€“ MongoDB supports searching by field, range queries, and regular expression searches. Queries can be made to return specific fields within documents.
๐ŸŸขIndexing โ€“ Indexes can be created to improve the performance of searches within MongoDB. Any field in a MongoDB document can be indexed.
๐ŸŸขReplication โ€“ MongoDB can provide high availability with replica sets. A replica set consists of two or more mongo DB instances. Each replica set member may act in the role of the primary or secondary replica at any time. The primary replica is the main server which interacts with the client and performs all the read/write operations. The Secondary replicas maintain a copy of the data of the primary using built-in replication. When a primary replica fails, the replica set automatically switches over to the secondary and then it becomes the primary server.
๐ŸŸขLoad balancing โ€“ MongoDB uses the concept of sharding to scale horizontally by splitting data across multiple MongoDB instances. MongoDB can run over multiple servers, balancing the load and/or duplicating data to keep the system up and running in case of hardware failure.

Data Modelling in MongoDB

Press enter or click to view image in full size

๐Ÿ”ธAs we have seen from the Introduction section, the data in MongoDB has a flexible schema. Unlike in SQL databases, where you must have a tableโ€™s schema declared before inserting data, MongoDBโ€™s collections do not enforce document structure. This sort of flexibility is what makes MongoDB so powerful.

When modeling data in Mongo, keep the following things in mind.

1.What are the needs of the application โ€“ Look at the business needs of the application and see what data and the type of data needed for the application. Based on this, ensure that the structure of the document is decided accordingly.
2.What are data retrieval patterns โ€“ If you foresee a heavy query usage then consider the use of indexes in your data model to improve the efficiency of queries.
3.Are frequent inserts, updates and removals happening in the database? Reconsider the use of indexes or incorporate sharding if required in your data modeling design to improve the efficiency of your overall MongoDB environment.

Difference between MongoDB & RDBMS

**๐ŸŸขSummary of RDBMS vs. MongoDB.

In a nutshell, MongoDB is a one-size-fits-all database based on a schema-less data representation which does not follow the traditional RDBMS model. The data is non-relational and it does not use SQL as a query language. RDBMS is a traditional database model that works on relational databases wherein data is stored in the form of the conventional row-column structure whereas MongoDB is a document-oriented model that has no concept of rows, columns, schemas, or SQL. Ultimately, you must decide what works best for you.**

MongoDB โ€“ Top 15 Interview Questions

  1. What is MongoDB? How is it different from SQL databases?

  2. What are Documents and Collections in MongoDB?

  3. Explain the structure of a MongoDB document.

  4. What is the difference between find() and findOne()?

  5. How do you create indexes in MongoDB? Why are they important?

  6. What is aggregation in MongoDB? Explain the aggregation pipeline.

  7. What are the differences between embedded documents and referenced documents?

  8. How do you implement schema validation in MongoDB?

  9. Explain the role of ObjectId in MongoDB.

  10. What is the purpose of the $lookup operator in aggregation?

  11. How do you handle relationships in MongoDB (1:1, 1:N, N:N)?

  12. How can you optimize queries in MongoDB?

  13. What is a capped collection in MongoDB?

  14. What is the difference between updateOne(), updateMany(), and replaceOne()?

  15. How does MongoDB ensure data durability and consistency?

more focus on topics sharding,replica sets,horizontal scaling

collection-table , document-row

๐Ÿ“Œ JSON vs BSON in MongoDB

FeatureJSON (JavaScript Object Notation)BSON (Binary JSON)
๐Ÿ”น FormatText-based (UTF-8)Binary-encoded
๐Ÿ”น Used InAPIs, config files, front-end data exchangeMongoDB internal storage & wire protocol
๐Ÿ”น Data TypesLimited (string, number, boolean, array, object, null)Rich types (Date, ObjectId, Binary, etc.)
๐Ÿ”น ReadabilityHuman-readableNot human-readable
๐Ÿ”น PerformanceSlower to parse (text)Faster (binary parsing is efficient)
๐Ÿ”น SizeSmaller size (for simple data)Slightly larger (stores metadata for types)
๐Ÿ”น SupportUniversal (language-independent)MongoDB-specific

๐Ÿง  Summary:

  • JSON = Good for data exchange, readability

  • BSON = Good for performance, extra data types, MongoDB efficiency

MongoDB stores data as BSON but accepts input/output as JSON-like syntax.

What is MongoDB? How is it different from SQL databases?

  • MongoDB is a NoSQL, document-based database that stores data in JSON-like documents (BSON).

  • It is schema-less, highly scalable, and designed for flexible and fast development.

๐Ÿ”„ SQL vs MongoDB:

FeatureMongoDBSQL (MySQL, PostgreSQL)
Data FormatDocuments (JSON/BSON)Tables with rows/columns
SchemaDynamic (schema-less)Fixed schema
Query LanguageMongoDB Query Language (MQL)Structured Query Language (SQL)
RelationshipsEmbedded or referencedJoins
ScalabilityHorizontal (Sharding)Vertical

Use MongoDB for apps with changing data structures, faster prototyping, or nested/complex data.

2.What are Documents and Collections in MongoDB?

  • A Document is a single record, like a row in SQL, but stored in JSON-like format.

{
  "_id": "123",
  "name": "John",
  "age": 25,
  "skills": ["JS", "MongoDB"]
}
  • A Collection is a group of documents, similar to a table in SQL.

    • Example: users collection holds all user documents.

โœ… Documents inside a collection can have different fields, unlike SQL rows which must follow table schema.

๐Ÿ“Œ 3**. Explain the structure of a MongoDB Document**

  • A MongoDB document is a BSON (Binary JSON) object.

  • It stores data as key-value pairs and supports nested structures.

๐Ÿ”ง Example document:


{
  _id: ObjectId("abc123"),    // Unique identifier (auto-generated if not given)
  name: "Alice",
  age: 28,
  email: "alice@example.com",
  address: {
    city: "Delhi",
    zip: "110001"
  },
  isActive: true,
  createdAt: ISODate("2024-01-01T10:00:00Z"),
  tags: ["student", "coder"]
}

๐Ÿง  Key Points:

  • Keys are strings, values can be:

    • Strings, Numbers, Booleans, Arrays, Embedded Documents, Dates, etc.
  • _id is mandatory and unique per document.

  • Flexible structure โ†’ documents in the same collection can vary in fields.


๐Ÿ“Œ 4**. Difference between find() and findOne() in MongoDB**

Featurefind()findOne()
ReturnsAll matching documents (cursor)First matching document
OutputCursor (use .toArray() to view)Direct document (object)
Use caseWhen you expect many resultsWhen you need just one
PerformanceSlightly heavierSlightly faster

๐Ÿ”ง Example:


db.users.find({ age: 25 })       // returns all users with age 25
db.users.findOne({ age: 25 })    // returns first user found with age 25

Use find() for lists or filtering, findOne() for login, profile fetch, etc.

๐Ÿ“Œ 5**. How do you create indexes in MongoDB? Why are they important?**

๐Ÿง  What is an Index?

  • An index is like a shortcut for MongoDB to find data faster, just like an index in a book.

  • Without indexes, MongoDB does a collection scan (checks every document).

โšก Why are indexes important?

  • Speeds up read/search queries.

  • Reduces CPU and memory usage.

  • Enables sorting and uniqueness constraints.

๐Ÿ”ง Creating Indexes:


db.users.createIndex({ name: 1 })      // Ascending index on 'name'
db.users.createIndex({ email: 1 }, { unique: true }) // Unique index

๐Ÿงน Remove Index:


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

Always index frequently queried, sorted, or filtered fields.


๐Ÿ“Œ 6**. What is Aggregation in MongoDB? Explain the Aggregation Pipeline**

๐Ÿง  What is Aggregation?

  • Aggregation is used to process data and return computed results (like SQL GROUP BY, SUM, AVG).

  • Useful for analytics, reports, summaries.


๐Ÿ”— Aggregation Pipeline (Processes documents in stages):


db.orders.aggregate([
  { $match: { status: "delivered" } },        // filter documents
  { $group: { _id: "$userId", total: { $sum: "$amount" } } },  // group by userId
  { $sort: { total: -1 } }                    // sort by total amount (desc)
])

๐Ÿ”ง Common Pipeline Stages:

StagePurpose
$matchFilters documents (like WHERE)
$groupGroups and applies aggregations
$sortSorts documents
$projectShapes the output (like SELECT)
$limit / $skipPagination

Aggregation = Chain of operations โ†’ Clean and powerful for data analysis.

๐Ÿ“Œ 7**. Difference between Embedded Documents and Referenced Documents**

๐Ÿงฑ Embedded Documents (Denormalized)

  • Stores related data inside the main document.

  • Better for read performance and fast access.


// Embedded Example
{
  name: "Alice",
  address: {
    city: "Delhi",
    zip: "110001"
  }
}

โœ… Use when data is closely related, not too large, and usually fetched together.


๐Ÿ”— Referenced Documents (Normalized)

  • Stores related data in separate collections and links them using _id or foreign key.

// Reference Example
{
  name: "Bob",
  addressId: ObjectId("abc123")
}
// Address stored in a separate collection

โœ… Use when data is large, reused, or changes independently.


๐Ÿ” Key Differences:

FeatureEmbeddedReferenced
PerformanceFaster readsSlower reads (requires join)
FlexibilityLess flexibleMore flexible
UpdatesHarder to update individuallyEasier to manage separately
Use WhenData is tightly coupledData is loosely coupled

๐Ÿ“Œ 8**. How do you implement Schema Validation in MongoDB?**

๐Ÿง  What is it?

Schema validation lets you define rules (like required fields, types, etc.) to enforce structure in collections.

๐Ÿงฐ Example using validator:


db.createCollection("users", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["name", "email"],
      properties: {
        name: { bsonType: "string" },
        email: { bsonType: "string", pattern: "^.+@.+\\\\..+$" },
        age: { bsonType: "int", minimum: 18 }
      }
    }
  }
})

๐Ÿงฉ Key Features:

  • Enforce types (string, int, bool, etc.)

  • Define required fields.

  • Add constraints like minimum, pattern, enum, etc.

Helps maintain data integrity, especially in teams/projects where structure matters.

๐Ÿ“Œ 9**. What is the Role of ObjectId in MongoDB?**

๐Ÿง  What is ObjectId?

  • It's the default unique identifier (_id) for MongoDB documents.

  • Ensures each document is uniquely identified within a collection.

๐Ÿ”ง Structure of ObjectId (12 bytes total):

PartBytesDescription
Timestamp4Creation time (to the second)
Machine identifier3Unique host identifier
Process ID2Process creating the ObjectId
Counter3Incrementing value to ensure unique

// Example
{
  _id: ObjectId("661facddf59a65b77e9032a1"),
  name: "Alice"
}

Benefits:

  • Automatically generated by MongoDB.

  • Encodes creation time โ†’ can be used for sorting by insertion time.

  • Guarantees global uniqueness without a central authority.


๐Ÿ“Œ 10**. What is the Purpose of $lookup in Aggregation?**

๐Ÿ”— What is $lookup?

  • $lookup performs a left outer join between two collections.

  • It combines related documents based on matching fields.

๐Ÿ”ง Example:


db.orders.aggregate([
  {
    $lookup: {
      from: "users",               // foreign collection
      localField: "userId",        // field in orders
      foreignField: "_id",         // field in users
      as: "userInfo"               // output array field
    }
  }
])

๐Ÿง  Key Points:

  • from: the other collection to join.

  • localField: your current document's field.

  • foreignField: field in the foreign collection to match.

  • as: name of the array to store matched documents.

โœ… Use Cases:

  • Getting user details with orders.

  • Joining product info with reviews, etc.

๐Ÿงฉ Think of $lookup as MongoDBโ€™s version of SQL JOIN.

๐Ÿ“Œ 11. How Do You Handle Relationships in MongoDB?

(MongoDB is NoSQL but you can still model relationships.)

๐Ÿ”— 1:1 Relationship

  • โœ… Embedded if tightly coupled.

{
  _id: 1,
  name: "John",
  profile: { age: 25, gender: "M" }
}
  • ๐Ÿ”— Reference if used independently.

{ _id: 1, name: "John", profileId: ObjectId("xyz123") }

๐Ÿ”— 1:N Relationship (One-to-Many)

  • โœ… Embed small/limited subdocs.

{
  _id: 1,
  title: "Blog Post",
  comments: [{ text: "Nice!" }, { text: "Thanks!" }]
}
  • ๐Ÿ”— Reference large/many records.

{ _id: 1, postId: ObjectId("xyz"), comment: "Great!" }

๐Ÿ”— N:N Relationship (Many-to-Many)

  • Always use referencing.

  • Example: Students & Courses


// Student
{ name: "A", courses: [ObjectId("c1"), ObjectId("c2")] }

// Course
{ name: "DSA", students: [ObjectId("s1"), ObjectId("s2")] }

๐Ÿ“Œ 12. How Can You Optimize Queries in MongoDB?

๐Ÿ” Tips to Make Queries Fast:

  1. โœ… Indexes

    • Create indexes on frequently queried, sorted, or filtered fields.

    db.users.createIndex({ email: 1 })
  1. ๐Ÿšซ Avoid collection scans

    • Use indexes to prevent scanning all documents.
  2. ๐ŸŽฏ Project only needed fields

    • Donโ€™t fetch unnecessary fields.

    db.users.find({}, { name: 1, email: 1 })
  1. ๐Ÿ“Œ Use $limit, $skip, $match early in aggregations

    • Reduces load by trimming data ASAP.
  2. ๐Ÿ’ก Avoid $where and regex unless indexed or optimized.

  3. ๐Ÿ“Š Use explain() to analyze performance

    
     db.users.find({ name: "John" }).explain("executionStats")
    
  4. ๐Ÿงฑ Avoid large embedded arrays โ€” slows down read/write.

  5. ๐Ÿ”ง Denormalize where helpful โ€” embedded docs help avoid joins.

๐Ÿ“Œ 13. What is a Capped Collection in MongoDB?

๐Ÿงฑ Definition:

  • A fixed-size collection that automatically overwrites oldest data when it reaches its limit.

  • Preserves insert order.

๐Ÿ”ง Key Features:

  • High write performance (no index updates).

  • Ideal for logs, real-time data, etc.

โœ… Example:


db.createCollection("logs", {
  capped: true,
  size: 1024 * 1024, // 1MB max size
  max: 1000          // Optional max documents
})

๐Ÿง  Think of it like a circular queue โ€“ oldest data gets deleted when full.


๐Ÿ“Œ 14**. Difference: updateOne(), updateMany(), replaceOne()**

MethodWhat it DoesUse Case
updateOne()Updates first matching documentChange one specific entry
updateMany()Updates all matching documentsBulk updates (e.g., status flag)
replaceOne()Replaces entire documentOverwrite with a new structure

๐Ÿ”ง Example:


db.users.updateOne({ name: "John" }, { $set: { age: 25 } })

db.users.updateMany({ active: false }, { $set: { banned: true } })

db.users.replaceOne({ name: "John" }, { name: "Johnny", age: 30 })

๐Ÿง  replaceOne() removes all old fields not in the new doc, unlike update.


๐Ÿ“Œ 15**. How Does MongoDB Ensure Data Durability & Consistency?**

๐Ÿ’พ Durability

  • Uses Write-Ahead Logging (WiredTiger engine).

  • Journaling: Before data is changed on disk, it's written to a journal file to recover after crash.

๐Ÿ” Write Concerns

  • You can configure writeConcern to control acknowledgment of writes.

    • "w: 1" = Acknowledged by primary (default).

    • "w: majority" = Acknowledged by majority of replicas โ†’ more durable.

๐Ÿ” Consistency

  • Achieved using replica sets (auto failover + replication).

  • Read/Write concerns let you control consistency guarantees:

    • E.g., readConcern: "majority" ensures reading the most up-to-date data.

๐Ÿง  Strong consistency is maintained on the primary, and eventual consistency on secondaries.

๐Ÿ“Œ MongoDB: Quick Overview

๐Ÿ”ท What is MongoDB?

  • A NoSQL, open-source, document-oriented database.

  • Stores data in flexible, JSON-like documents (BSON format).

  • Designed for scalability, high availability, and performance.


๐Ÿ”น Core Concepts

ConceptDescription
DocumentA single record, stored in BSON (Binary JSON) format. Example: { name: "Alice", age: 25 }
CollectionGroup of related documents (like a table in SQL).
DatabaseContainer for collections (like a schema in SQL).
_idUnique identifier for every document (auto-generated ObjectId).
Schema-lessFields can vary across documents in the same collection.

๐Ÿ”น Key Features

  • โœ… Flexible Schema: Easily adapt data structure.

  • โœ… Horizontal Scalability: Built-in sharding support.

  • โœ… Replication: High availability using replica sets.

  • โœ… Indexing: Improves read/query performance.

  • โœ… Aggregation Framework: For data processing & transformation.


๐Ÿ”น Common Commands


// Create
db.users.insertOne({ name: "John", age: 22 })

// Read
db.users.find({ age: { $gt: 20 } })

// Update
db.users.updateOne({ name: "John" }, { $set: { age: 25 } })

// Delete
db.users.deleteOne({ name: "John" })

๐Ÿ”น Use Cases

  • Realtime applications (e.g., chats, feeds)

  • Content management systems

  • IoT & big data solutions

  • Mobile + web app backends

๐Ÿ“Œ What is MongoDB?

MongoDB is an open-source, NoSQL database that stores data in JSON-like documents using a flexible, schema-less format. It is designed for modern applications that require fast, scalable, and flexible data storage. MongoDB offers horizontal scalability through sharding, high availability through replica sets, and powerful querying through its aggregation framework.


๐Ÿ“Œ Core Concepts of MongoDB

1. Document

  • Document: The basic unit of data in MongoDB, stored as BSON (Binary JSON) format.

  • Documents can be nested and can have different fields, making MongoDB very flexible in handling dynamic data structures.

  • Example:

    
      {
        "_id": ObjectId("60f5a7f08e1c4e1d93fb1234"),
        "name": "John Doe",
        "age": 29,
        "address": {
          "street": "123 Elm St",
          "city": "New York"
        }
      }
    

2. Collection

  • A collection is a group of documents that are stored together.

  • Collections are schema-less, meaning documents within the same collection don't need to have the same structure or fields.

  • Collections are similar to tables in relational databases.

3. Database

  • A database is a container for collections.

  • MongoDB allows multiple databases, each having its own set of collections.

  • Example: A Blog database might have collections for posts, comments, and users.

4. _id Field

  • Every document has a unique _id field, which serves as the primary key. MongoDB automatically creates an ObjectId for this field if not provided.

  • ObjectId is a 12-byte identifier used by MongoDB to ensure uniqueness.


๐Ÿ“Œ MongoDB Architecture

1. MongoDB Server

The MongoDB server provides the core database functionality, including managing databases, collections, and documents.

Components:

  • mongod: The MongoDB daemon process responsible for managing database operations.

  • mongos: A routing service that manages distributed operations in a sharded cluster.

2. Replica Sets

  • A Replica Set is a group of mongod instances that maintain the same data set, providing data redundancy and high availability.

  • Primary: The main server handling all write operations.

  • Secondary: Copies of the primary node that handle read operations and provide data redundancy.

  • If the primary node fails, one of the secondary nodes is automatically promoted to primary.

3. Sharding

  • Sharding allows MongoDB to distribute data across multiple servers, enabling horizontal scaling.

  • The data is divided into chunks and distributed across shards.

  • Shard Key: A field used to partition data. This key is chosen based on the query patterns to ensure even distribution.

  • Mongos: A routing service that directs client requests to the appropriate shard based on the shard key.


๐Ÿ“Œ MongoDB Data Types

MongoDB supports several BSON data types, including:

  • String: A UTF-8 encoded string.

  • Integer: 32-bit or 64-bit integers.

  • Boolean: Represents true/false.

  • Double: 64-bit floating-point values.

  • Array: A list of elements.

  • Object: A nested document.

  • ObjectId: A unique 12-byte identifier.

  • Date: Stores date and time.

  • Null: Represents a null value.

  • Binary Data: Stores binary data (e.g., images, files).

  • Regular Expression: For storing regular expressions.


๐Ÿ“Œ CRUD Operations in MongoDB

  1. Create:

    • insertOne(): Inserts a single document.

    • insertMany(): Inserts multiple documents at once.

Example:


    db.users.insertOne({ name: "Alice", age: 30 })
  1. Read:

    • find(): Retrieves documents matching query conditions.

    • findOne(): Retrieves a single document matching query conditions.

Example:


    db.users.find({ age: { $gt: 25 } })
  1. Update:

    • updateOne(): Updates a single document.

    • updateMany(): Updates multiple documents.

    • replaceOne(): Replaces a document entirely.

Example:


    db.users.updateOne({ name: "Alice" }, { $set: { age: 31 } })
  1. Delete:

    • deleteOne(): Deletes a single document.

    • deleteMany(): Deletes multiple documents.

Example:


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

๐Ÿ“Œ Indexes in MongoDB

Indexes are crucial for improving the performance of read operations. MongoDB supports several types of indexes:

  • Single Field Index: Default index on a single field.

  • Compound Index: Index on multiple fields.

  • Geospatial Index: For handling location-based data.

  • Text Index: For full-text search.

Example of creating an index:



db.users.createIndex({ name: 1 }) // Ascending index on the 'name' field.

๐Ÿ“Œ Aggregation Framework

The aggregation framework allows you to process and transform data. It works by passing documents through a series of pipeline stages.

Common Stages:

  • $match: Filters documents based on conditions (similar to find()).

  • $group: Groups documents by a specific field.

  • $sort: Sorts documents by a field.

  • $project: Specifies which fields to include/exclude.

  • $lookup: Joins data from another collection (similar to SQL JOIN).

Example:


db.orders.aggregate([
  { $match: { status: "completed" } },
  { $group: { _id: "$customerId", totalAmount: { $sum: "$amount" } } }
])

๐Ÿ“Œ Replication in MongoDB

Replication in MongoDB ensures high availability and data redundancy through replica sets.

  • Primary: Only one primary replica in a replica set that handles all write operations.

  • Secondaries: Replicas of the primary that handle read operations.

  • Automatic Failover: If the primary goes down, a secondary is automatically promoted to primary.


๐Ÿ“Œ Sharding in MongoDB

Sharding allows MongoDB to distribute large datasets across multiple servers, ensuring that the database can scale horizontally.

  • Shard Key: A field that MongoDB uses to distribute data across shards.

  • Chunks: Data is split into chunks based on the shard key and distributed across multiple shards.

  • Mongos: The routing service that directs client requests to the correct shard.


๐Ÿ“Œ MongoDB Write Concern and Read Concern

  • Write Concern: Defines the level of acknowledgment requested from MongoDB for write operations.

    • "w: 1": Acknowledgment from the primary node.

    • "w: majority": Acknowledgment from a majority of nodes.

  • Read Concern: Defines the consistency level for read operations.

    • "local": Reads the most recent data available.

    • "majority": Ensures the read is from the majority of replica set members.


๐Ÿ“Œ MongoDB Internals

1. WiredTiger Storage Engine

  • MongoDB's default storage engine, which uses document-level concurrency control and compression for storage.

  • Supports multi-version concurrency control (MVCC) to ensure consistent reads without blocking writes.

2. Journaling

  • Journaling ensures that data is not lost even if the system crashes. MongoDB writes data to a journal file before making changes to the database.

๐Ÿ“Œ Security in MongoDB

  1. Authentication: MongoDB supports multiple authentication mechanisms, including SCRAM, LDAP, and x.509 certificates.

  2. Authorization: MongoDB provides role-based access control (RBAC) to restrict users' access to different resources.

  3. Encryption: MongoDB supports encryption at rest and in transit to protect data.


๐Ÿ“Œ MongoDB Use Cases

  • Real-time analytics (e.g., IoT, logs)

  • Content management (e.g., blogging platforms)

  • Mobile apps (e.g., user profiles)

  • Gaming (e.g., player data)

  • E-commerce (e.g., product catalogs)