Mongodb Guide

What is a Document in MongoDB

1. Definition

A document in MongoDB is a single record that stores data in a JSON-like format called BSON. It is the basic unit of data in MongoDB, similar to a row in a SQL table.

2. When to Use Document

  • When storing user data or application data
  • When data structure can vary
  • When working with JSON-based applications
  • When storing nested or hierarchical data

3. Where it is Used

  • Inside collections in MongoDB
  • Web applications (user profiles, products, orders)
  • APIs and backend services
  • Real-time applications

4. Why We Use Documents

  • Flexible structure (no fixed schema)
  • Supports nested data
  • Easy to read and write
  • Matches JavaScript object format

5. How Document Works

  • Stored as key-value pairs
  • Can include arrays and nested objects
  • Each document has a unique _id field
  • Stored inside a collection

Basic Syntax

{
  name: "Manaswini",
  age: 22,
  role: "Developer"
}

Real Example

{
  _id: ObjectId("123abc"),
  name: "Manaswini",
  skills: ["React", "Node.js"],
  address: {
    city: "Chennai",
    country: "India"
  }
}

6. Explanation

  • Data is stored in key-value format
  • Supports nested objects and arrays
  • Each document is unique using _id
  • Represents real-world entities easily

7. Advantages

  • Flexible and schema-less
  • Easy to map with JavaScript objects
  • Supports complex data structures
  • Fast data retrieval

8. Disadvantages

  • Data duplication can occur
  • No strict structure enforcement
  • Large documents can impact performance

Interview Points

  • Document = single record in MongoDB
  • Stored in JSON/BSON format
  • Contains key-value pairs
  • Has a unique _id field
  • Stored inside collections