Explain MongoDB's data hierarchy: Database, Collection, Document.

Beginner

Answer

MongoDB organizes data in a three-level hierarchy:

Database: Top-level container for collections

  • Contains multiple collections
  • Each database has its own files on disk
  • Default databases: admin, local, config

Collection: Group of MongoDB documents

  • Equivalent to a table in RDBMS
  • Documents in a collection can have different schemas
  • Collections are created automatically when first document is inserted

Document: Individual record in a collection

  • JSON-like structure stored as BSON
  • Can contain nested documents and arrays
  • Maximum size: 16MB

Example structure:

Database: ecommerce
├── Collection: users
│   ├── Document: {_id: 1, name: "John", email: "john@email.com"}
│   └── Document: {_id: 2, name: "Jane", age: 25, city: "NYC"}
└── Collection: products
    └── Document: {_id: 1, title: "Laptop", price: 999.99}