AD JB Toolbox 01 EN

What Is MongoDB? Features, Document Modeling and When to Use It

MongoDB is a database that stores data as documents rather than organizing it primarily into relational tables. Consider it for data commonly read together, such as product catalogs with varying attributes or nested user profiles, while still designing the schema and checking performance.

This guide explains MongoDB’s storage model, features, use cases and adoption criteria. For the wider landscape, see the comparison of NoSQL models and relational databases.

How does MongoDB store data?

A document consists of field-and-value pairs. A collection is a logical grouping of documents, and a database can contain collections for different purposes, such as products, orders and customers.

MongoDB stores documents as BSON (Binary JSON). BSON expresses JSON (JavaScript Object Notation) structures in binary form and supports additional types, including dates and ObjectId values. MongoDB should therefore not be understood as a store that simply saves JSON text files. The document reference explains types and identifier rules.

This fictional product JSON illustrates the shape of a document. In a standard collection, _id identifies a document. The example uses a readable string; an application still needs an identifier format and duplicate-handling rules.

{
  "_id": "book-101",
  "name": "Database Basics",
  "category": "books",
  "price_krw": 24000,
  "attributes": {
    "author": "Mina Kim",
    "pages": 320
  },
  "tags": [
    "database",
    "beginner"
  ]
}

attributes is a nested object and tags is an array. Books can have author and page fields while electronics have battery information. Preserve shared rules for price types, required fields and missing values.

Main features and their conditions

Flexible schema and validation

A schema defines fields, types and required conditions. MongoDB does not require every document in a collection to have identical fields by default. That flexibility does not eliminate schema design.

Schema validation can constrain allowed types and value ranges. Coordinate application checks and database validation to prevent mixed number/string prices or inconsistent date representations. Before adding rules to existing data, identify nonconforming documents and decide how updates will be handled.

Queries, aggregation and related data

MongoDB queries use field conditions and operators rather than accepting SQL statements unchanged. Learn the syntax used by your language’s driver or the shell. Dot notation accesses nested fields, and queries can also express array conditions.

An aggregation pipeline processes documents through stages such as filtering, grouping and calculation. For example, filter noncancelled order items and total quantities by product. The aggregation-pipeline guide explains how stages work.

$lookup provides a left outer join to another collection, so “MongoDB has no joins” is inaccurate. Review $lookup support and performance conditions. Do not assume that references automatically receive the referential-integrity enforcement associated with relational foreign-key constraints.

Indexes and performance

An index is a data structure that can reduce the data examined to find matching documents. Single-field and compound indexes serve different access patterns. The index documentation explains both query benefits and write costs.

More indexes require storage and work to maintain them during writes. Performance also depends on document size, read/write mix, memory, disks and networking. Evaluate representative queries using execution plans and realistic load instead of assuming NoSQL is inherently fast.

Transactions and read/write guarantees

A single-document update is atomic: it does not partially apply that update. For changes that must succeed or fail together across documents, consider multi-document transactions on replica sets or sharded clusters. Do not assume the same capability exists on a standalone server.

ACID means Atomicity, Consistency, Isolation and Durability. Review deployment and configuration conditions in the transaction documentation. When order creation and inventory reduction affect separate documents, define transaction boundaries, concurrent-request handling and retry behavior.

Read concern controls the data state a read may observe, while write concern controls the acknowledgment level for a write. Establish the guarantees needed before telling a user that a payment is complete, and distinguish operations that can accept older values from replicas.

Should related data be embedded or referenced?

Embedding puts related data inside one document. Referencing links to another document’s identifier. The modeling guide recommends storing together what is accessed together; the embedding-versus-references guide explains the tradeoffs for relationships and updates.

Decision area Consider embedding when Consider references when
Reading Parent and related details are normally read together Related details are read independently
Updating Values belong to one update unit Shared information changes independently
Size The group has a bounded size and count Items keep growing or are large
Examples An order’s delivery address and purchased product name Full review history or a shared customer profile

Copying a delivery address into an order can preserve its historical meaning. Copying a customer’s current contact details into every order creates copies to maintain when those details change. First distinguish historical facts from values that must always be current.

A regular BSON document has a maximum size of 16 MiB. Appending every comment or log entry to one array can encounter that limit and increase update costs. Use separate collections, references or bounded groups with the document-size limit in mind.

Which use cases deserve consideration?

These are reasons to evaluate a document model, rather than guarantees based on industry labels. Actual reads and updates should drive the choice.

Use case Reason to consider documents Conditions to check
Product catalog Different attributes and nested product details Shared-field validation and filtering/sorting indexes
Profiles and content Related properties read on one screen Access permissions, large arrays and duplicated data
Events and device records Event-specific structure and extra properties Retention, device/time queries and capacity growth
Orders A snapshot of the order’s state Inventory/payment correctness, concurrent updates and transactions

Also compare relational databases when flexible cross-table reporting, shared relationships and constraints, or complex many-to-many updates are central requirements. Storing JSON alone does not justify replacing an existing database. Check whether a document model improves the important queries and operational workload.

A small insert-and-query example

The following commands use MongoDB Shell, mongosh. Connect to a separate practice deployment first, using an account with read, write and index-creation permissions for the target database and an installed shell. See the MongoDB Shell documentation for connection instructions.

The example inserts one product into product_catalog in the mongodb_intro_demo database. Start with an empty collection of this name in a practice environment, and verify that your connection targets that environment before running the commands.

db = db.getSiblingDB("mongodb_intro_demo");

db.product_catalog.insertMany([
{
  "_id": "book-101",
  "name": "Database Basics",
  "category": "books",
  "price_krw": 24000,
  "attributes": {
    "author": "Mina Kim",
    "pages": 320
  },
  "tags": [
    "database",
    "beginner"
  ]
}
]);

insertMany() inserts documents. Repeating the same _id in a standard collection produces a duplicate-key error. For repeated practice, use a fresh practice database or explicitly identify and handle only the sample document you added. Do not delete an existing collection to resolve that error.

This query finds products in books priced below 30,000 Korean won, returns their identifiers, names and prices, and sorts by ascending price. With only the sample data present, book-101 matches the conditions.

db.product_catalog.find(
  { category: "books", price_krw: { $lt: 30000 } },
  { _id: 1, name: 1, price_krw: 1 }
).sort({ price_krw: 1 });

$lt means “less than.” The second object specifies returned fields, a projection, and 1 in sort() means ascending order. The find() reference explains filters and projections.

For frequent category-specific price filters and sorting, consider this compound index. Examine the actual distribution and other queries before applying createIndex() in production.

db.product_catalog.createIndex(
  { category: 1, price_krw: 1 }
);

The following command executes the query and reports execution statistics without changing documents. In the explain("executionStats") results, inspect the chosen plan, keys and documents examined, and documents returned. A small collection may use a collection scan; merely creating an index does not demonstrate a speed improvement.

db.product_catalog.find(
  { category: "books", price_krw: { $lt: 30000 } }
).sort({ price_krw: 1 }).explain("executionStats");

Replication and sharding have different jobs

A replica set is a group of servers maintaining the same data. Typically, a primary accepts writes and secondaries replicate changes; eligible members can elect a new primary after a failure. The replication guide explains elections and asynchronous replication.

Failover can cause temporary write delays or errors, and secondary reads can reflect replication lag. Replication does not unconditionally guarantee uninterrupted service or prevent every loss of data. Design retries, duplicate-request handling and required read/write guarantees together with the application.

Sharding distributes data across servers for horizontal scaling. A shard key contains the fields used for distribution and query routing. Concentrated keys or queries that must visit every shard can limit the benefit. The sharding guide explains key selection and operational complexity.

Replication and sharding can be used together, but serve different purposes. Check the model, indexes and current bottlenecks before introducing sharding simply because data might grow. There should be a reason to accept its extra complexity and cost.

What should you check before adopting MongoDB?

  1. Define important operations. Specify filters, ordering and update units for product details, category price searches and order creation; compare actual relational and document implementations.
  2. Review the model and correctness. Decide on embedding or references, document size, validation, indexes, transactions and immediate-read requirements.
  3. Compare representative load. Measure latency, throughput and errors with realistic data and request distribution. Record versions, hardware and settings, and examine failure and recovery scenarios.
  4. Choose an operating model. Decide between self-management and a managed service, assigning responsibility for backup, restoration, monitoring, upgrades and support.
  5. Prepare migration and a route back. Define identifier/type conversions, missing-data checks, writes during cutover and conditions for returning to the existing store.

MongoDB Atlas is a managed cloud service with a different division of operational responsibility from a self-managed deployment. Use the Atlas documentation to check the necessary features and deployment options. Include storage, backups, networking and operational work alongside instance costs.

For production, review least-privilege accounts, encrypted connections, network restrictions and credential management using the security guidance appropriate to your deployment. An accidental deletion can propagate to replicas, so replication does not replace backup. Follow the backup-method guidance and verify that restoration actually works.

More in This Category
JRE vs JDK: Differences, JVM and Which Java Package to Install

JRE vs JDK: Differences, JVM and Which Java Package to Install

Compare Java runtime and development packages, understand the JVM’s role, and choose the right installation. Includes modern packaging changes, executable checks, compilation examples and common launch errors.

File Hashes: MD5, SHA-1, SHA-256 and How to Verify Downloads

File Hashes: MD5, SHA-1, SHA-256 and How to Verify Downloads

Learn how file hashes work, compare MD5, SHA-1, and SHA-256, and verify downloads with practical commands. Understand trusted reference checksums, mismatches, and why password storage needs a different hashing method.

What Is NoSQL? Data Models, SQL Differences and When to Use It

What Is NoSQL? Data Models, SQL Differences and When to Use It

Understand the four main NoSQL data models and compare them with relational databases. Learn how schema design, transactions, consistency and distribution affect the decision to adopt a NoSQL product.

EditPlus: How to Connect to a Remote Server Using FTP or SFTP

Learn how to configure FTP or SFTP accounts in EditPlus, open remote files and verify that saved changes reach the server. The guide covers protocol and port selection, authentication, directory browsing and common connection or permission errors.

What Is MongoDB? Features, Document Modeling and When to Use It

What Is MongoDB? Features, Document Modeling and When to Use It

Learn how MongoDB documents, validation, indexes and transactions work. A product example and modeling comparison explain use cases, replication versus sharding, and the operational checks needed before adoption.

What Is React? Key Concepts and Differences from jQuery

What Is React? Key Concepts and Differences from jQuery

Understand components, JSX, props, and state, then compare how React and jQuery update a page. Run equivalent counter examples and learn which approach fits your project.