What is a Document in MongoDB: Definition and Examples
document is a basic unit of data stored in a collection, similar to a row in a table but more flexible. It is a JSON-like object that holds data as key-value pairs, allowing nested structures and arrays.How It Works
Think of a MongoDB document like a digital file folder that holds information about one thing, such as a person or a product. Instead of fixed columns like in a spreadsheet, each document can have different fields, making it very flexible.
Each document is stored in a collection, which is like a drawer holding many folders. Documents use a format similar to JSON, so they can include nested objects and lists, allowing you to represent complex data easily.
This flexibility means you can add or remove fields in documents without affecting others, making MongoDB great for evolving data needs.
Example
This example shows a MongoDB document representing a book with various details stored as key-value pairs.
db.books.insertOne({
title: "The Great Gatsby",
author: "F. Scott Fitzgerald",
year: 1925,
genres: ["Novel", "Historical"],
available: true
})
// To find the document:
db.books.find({ title: "The Great Gatsby" })When to Use
Use MongoDB documents when you need a flexible way to store data that can change over time or vary between entries. They are ideal for applications like user profiles, product catalogs, or content management where each item might have different attributes.
Documents work well when you want to store complex data with nested details without designing a strict schema upfront, making development faster and more adaptable.
Key Points
- A document is a JSON-like object storing data as key-value pairs.
- Documents are stored in collections, similar to tables in relational databases.
- They allow flexible and nested data structures.
- Each document can have different fields, supporting evolving data needs.