Skip to main content

MongoDB Documents

Introduction

Documents are the core building blocks of MongoDB's data model. Unlike traditional relational databases that use tables and rows, MongoDB stores data in flexible, JSON-like documents. This document-oriented approach provides a natural way to represent and work with data without rigid schemas.

In this guide, you'll learn about MongoDB documents, their structure, how to create and manipulate them, and best practices for document design.

What are MongoDB Documents?

A MongoDB document is a set of key-value pairs stored in BSON (Binary JSON) format. BSON extends the JSON model to provide additional data types and efficiency for data storage and retrieval.

Key Characteristics of MongoDB Documents

  • Schema-less: Documents in the same collection can have different fields
  • Field-value structure: Each field has a specific value of a specific data type
  • Unique identifier: Each document has a mandatory _id field that serves as a primary key
  • Nested structures: Documents can contain arrays and other documents as values

Document Structure

A basic document looks like this:

javascript
{
_id: ObjectId("60a67c926dfa5f68ee7ecfb9"),
name: "John Doe",
age: 30,
email: "[email protected]",
active: true
}

The _id Field

Every MongoDB document requires a unique _id field that acts as a primary key. If you don't specify one when inserting a document, MongoDB automatically generates an ObjectId for this field.

javascript
// MongoDB automatically adds an _id if not specified
db.users.insertOne({
name: "Sarah Smith",
age: 28
});

// The result includes the generated _id
// {
// acknowledged: true,
// insertedId: ObjectId("60a67c926dfa5f68ee7ecfb9")
// }

Data Types in MongoDB Documents

MongoDB supports a variety of data types for document fields:

Data TypeDescriptionExample
StringUTF-8 character strings"Hello World"
Integer32-bit or 64-bit integer42
Double64-bit IEEE 754 floating point3.14159
BooleanTrue or false valuestrue
ArrayList or multiple values["red", "green", "blue"]
ObjectEmbedded documents{ name: "John", age: 30 }
DateDateTime stored as 64-bit integernew Date()
ObjectId12-byte identifierObjectId("60a67c926dfa5f68ee7ecfb9")
NullNull valuenull

Creating and Inserting Documents

MongoDB provides several methods to insert documents into collections.

Insert a Single Document

javascript
// Insert one document
db.products.insertOne({
name: "Smartphone",
price: 699.99,
category: "Electronics",
features: ["5G", "12MP Camera", "128GB Storage"],
inStock: true
});

// Output:
// {
// acknowledged: true,
// insertedId: ObjectId("60a67c926dfa5f68ee7ecfba")
// }

Insert Multiple Documents

javascript
// Insert multiple documents
db.products.insertMany([
{
name: "Laptop",
price: 1299.99,
category: "Electronics",
features: ["16GB RAM", "1TB SSD", "15.6-inch display"]
},
{
name: "Headphones",
price: 199.99,
category: "Accessories",
features: ["Noise cancellation", "Wireless", "30-hour battery"]
}
]);

// Output:
// {
// acknowledged: true,
// insertedIds: {
// 0: ObjectId("60a67c926dfa5f68ee7ecfbb"),
// 1: ObjectId("60a67c926dfa5f68ee7ecfbc")
// }
// }

Querying Documents

MongoDB provides a flexible query language to retrieve documents from collections.

Finding Documents

To retrieve all documents in a collection:

javascript
// Find all documents
db.products.find();

// Output: All documents in the products collection

To find documents that match specific criteria:

javascript
// Find products in the Electronics category
db.products.find({ category: "Electronics" });

// Output: Documents where category is "Electronics"

Query Operators

MongoDB provides various operators to build complex queries:

javascript
// Find products with a price less than 500
db.products.find({ price: { $lt: 500 } });

// Find products that are electronics or accessories
db.products.find({
category: { $in: ["Electronics", "Accessories"] }
});

Projections

You can specify which fields to include or exclude in the query results:

javascript
// Include only name and price fields
db.products.find({}, { name: 1, price: 1 });

// Exclude the features field
db.products.find({}, { features: 0 });

Updating Documents

MongoDB provides multiple ways to update documents.

Update a Single Document

javascript
// Update one document
db.products.updateOne(
{ name: "Smartphone" },
{ $set: { price: 649.99, onSale: true } }
);

// Output:
// {
// acknowledged: true,
// matchedCount: 1,
// modifiedCount: 1
// }

Update Multiple Documents

javascript
// Update all electronics products
db.products.updateMany(
{ category: "Electronics" },
{ $set: { warranty: "2 years" } }
);

// Output:
// {
// acknowledged: true,
// matchedCount: 2,
// modifiedCount: 2
// }

Update Operators

MongoDB provides various update operators:

  • $set: Sets field values
  • $inc: Increments field values
  • $push: Adds elements to arrays
  • $pull: Removes elements from arrays
  • $unset: Removes fields

Example:

javascript
// Increment the price by 10 and add a tag
db.products.updateOne(
{ name: "Laptop" },
{
$inc: { price: 10 },
$push: { tags: "premium" }
}
);

Deleting Documents

Delete a Single Document

javascript
// Delete one document
db.products.deleteOne({ name: "Headphones" });

// Output:
// {
// acknowledged: true,
// deletedCount: 1
// }

Delete Multiple Documents

javascript
// Delete all out-of-stock products
db.products.deleteMany({ inStock: false });

// Output:
// {
// acknowledged: true,
// deletedCount: 3
// }

Nested Documents

MongoDB documents can contain other documents, creating nested structures.

javascript
// Document with nested information
db.customers.insertOne({
name: "Alice Johnson",
contact: {
email: "[email protected]",
phone: "555-123-4567",
address: {
street: "123 Main St",
city: "Springfield",
state: "IL",
zip: "62701"
}
},
orders: [
{ id: "ORD-001", total: 99.99, date: new Date("2023-01-15") },
{ id: "ORD-002", total: 149.99, date: new Date("2023-02-03") }
]
});

Querying Nested Documents

To query fields in nested documents, use dot notation:

javascript
// Find customers from Springfield
db.customers.find({ "contact.address.city": "Springfield" });

// Find customers with orders over $100
db.customers.find({ "orders.total": { $gt: 100 } });

Document Size Limits and Best Practices

Document Size Constraints

  • MongoDB has a maximum BSON document size of 16 megabytes
  • This limit helps ensure good performance and prevents excessive memory usage

Best Practices for Document Design

  1. Balance between embedding and referencing:
    • Embed related data that you query together frequently
    • Reference separate collections for data accessed independently or very large datasets
javascript
// Embedding example (good for 1:few relationships)
db.posts.insertOne({
title: "MongoDB Document Design",
content: "This is a post about document design...",
comments: [
{ user: "user1", text: "Great post!" },
{ user: "user2", text: "Thanks for sharing." }
]
});

// Referencing example (good for 1:many relationships)
db.authors.insertOne({
_id: ObjectId("60a67c926dfa5f68ee7ecfbd"),
name: "Jane Smith",
bio: "Tech writer and educator"
});

db.books.insertOne({
title: "MongoDB Basics",
authorId: ObjectId("60a67c926dfa5f68ee7ecfbd"),
year: 2022
});
  1. Plan for data growth:

    • Arrays can grow in size - be cautious with unbounded arrays
    • Consider the future size of documents when embedding
  2. Design for your access patterns:

    • Structure documents to match how your application queries and updates data
    • It's okay to denormalize data if it improves read performance
  3. Consider indexing needs:

    • Structure documents to allow efficient indexing on common query fields

Real-World Example: E-Commerce Product Catalog

Let's create a practical example of how MongoDB documents can be used for an e-commerce product catalog:

javascript
// Product document
db.products.insertOne({
name: "Ergonomic Office Chair",
sku: "FURN-CH-ERG-001",
price: 249.99,
discountPrice: 199.99,
category: "Furniture",
subcategory: "Office Chairs",
vendor: {
id: "VENDOR-123",
name: "ErgoDesigns",
rating: 4.8
},
specs: {
dimensions: {
height: "45 inches",
width: "27 inches",
depth: "26 inches"
},
weight: "35 pounds",
maxWeight: "300 pounds",
materials: ["Mesh", "Aluminum", "Memory Foam"]
},
colors: [
{ name: "Black", hex: "#000000", inStock: true },
{ name: "Gray", hex: "#808080", inStock: false },
{ name: "Blue", hex: "#0000FF", inStock: true }
],
features: [
"Adjustable height",
"Lumbar support",
"360-degree swivel",
"Armrest padding"
],
inventory: {
warehouse: [
{ location: "East", quantity: 23 },
{ location: "West", quantity: 14 }
],
totalAvailable: 37,
lowStockThreshold: 10
},
ratings: {
average: 4.6,
count: 127
},
created: new Date(),
lastModified: new Date()
});

This document structure:

  • Contains basic product information (name, price, etc.)
  • Includes vendor details as a nested document
  • Stores color options as an array of documents
  • Maintains inventory information across multiple warehouses
  • Tracks customer ratings

Summary

MongoDB documents are the fundamental data structure in MongoDB's document-oriented database model. They offer flexibility through their schema-less design while providing rich structure through nested documents and arrays. Key points to remember:

  • Documents are stored as BSON, a binary representation of JSON with additional data types
  • Each document requires a unique _id field
  • Documents can contain fields with various data types, including other documents and arrays
  • MongoDB provides rich operations for creating, reading, updating, and deleting documents
  • Design your document structure based on your application's query patterns and data relationships

Exercises

  1. Create a MongoDB document representing a user profile with personal information, contact details, and a list of interests.
  2. Write a query to find all users living in a specific city and with a particular interest.
  3. Update a document to add a new field to all documents in a collection.
  4. Design a document schema for a blog application with posts, comments, and user information.
  5. Practice querying nested fields in documents using dot notation.

Additional Resources

Remember that effective MongoDB document design requires understanding your application's specific needs and access patterns. As you gain experience, you'll develop an intuition for when to embed related data and when to use references across collections.



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)