Skip to content
Tutorials Center
My learning

Topics

Lesson 1 of 70 ยท Getting started

What Is MongoDB?

Learn what MongoDB is, how documents, collections and databases fit together, how it differs from relational databases, and when it is the right choice.

MongoDB is a document database. Instead of storing data in tables made of rows and columns, it stores documents: self-describing records that look like JSON objects, with named fields, nested objects and arrays. A document usually holds everything you need to know about one thing, such as a product with its specs and tags, or an order with its line items.

This lesson gives you the mental model for the whole tutorial: what a document, a collection and a database are, how that differs from the relational model you may know from SQL, and when MongoDB is a good fit. You will also see how this site lets you practice without a MongoDB server.

Real MongoDB versus the practice engine. The commands in the read-only code blocks are real mongosh commands. The site cannot run a database server in your browser, so every <TryIt> in this tutorial uses a small stand-in: a hand-written JavaScript mini engine that applies MongoDB-style filters, updates and aggregation stages to plain arrays of objects. It copies the behaviour of MongoDB for the cases we teach, but it is not MongoDB. The Practice Engine Used in This Tutorial lists exactly what it does and does not emulate.

The MongoDB hierarchy

Database A named container for collections.
Collection A group of related documents.
Document One record with fields, objects and arrays.

A collection is roughly a table, a document roughly a row.

1 / 2

Documents, collections and databases

A document is a set of field: value pairs. MongoDB stores it in a binary format called BSON (you will meet it in BSON Types), but you write and read it as JSON-like text:

JavaScript
{
  _id: 1,
  name: "Trail Shoe",
  price: 89,
  tags: ["running", "outdoor"],
  specs: { weight: 280, waterproof: true }
}

Values can be strings, numbers, booleans, dates, nested documents, arrays and more. Every document has an _id field that is unique inside its collection, and MongoDB adds one for you when you do not supply it.

Documents live in a collection, for example products or orders. A collection has no fixed column list: one document may have a specs field and the next may not. Collections live in a database, and one MongoDB server can host many databases. In mongosh, the shell you will install in the next lesson, you work with them like this:

JavaScript
use shop                       // switch to the "shop" database (created on first write)
db.products.insertOne({ name: "Yoga Mat", price: 30 })
db.products.find({ price: { $lt: 50 } })

db means "the current database", and db.products is the collection named products. Collections and databases are created lazily, the first time you write data into them.

Flexible shapes in a collection

"Schema-less" is a common description, but "flexible schema" is more accurate. Your application always has an expected shape, and MongoDB simply does not force every document to follow one unless you ask it to (see Schema Validation). This is handy when records really do vary, for example products with different attributes, or when your model changes often.

The first stand-in below builds a small products collection where documents differ, then filters it the way find would.

JS One collection, different shapes

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that the second product has no specs at all, and nothing breaks. Query code has to cope with fields that are absent, which is why MongoDB has operators like $exists (Element and Evaluation Operators).

Documents versus relational rows

In a relational database you split an order across several tables and join them back together at query time. In MongoDB you often store the order as one document that already contains its customer details and line items:

JavaScript
{
  _id: 1,
  placed: "2026-03-01",
  customer: { id: 7, name: "Mia" },
  items: [
    { sku: "A1", qty: 2 },
    { sku: "B2", qty: 1 }
  ]
}

Reading that order is one lookup by _id, and writing it is atomic because it is one document. The cost is duplication: Mia's name now appears inside every order she placed, so a rename has to touch many documents. Choosing between embedding data and referencing it is the central skill of MongoDB design, covered in Embedding vs Referencing.

The second stand-in counts how many "reads" each approach needs to rebuild one order.

JS Three tables versus one document

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Real databases do much more than this toy count (indexes, caching, joins done in the server), so do not read it as a benchmark. It only shows the shape difference: related data that is read together can be stored together.

NoSQL families, and MongoDB next to SQL databases

"NoSQL" is not one technology. It is a label for databases that do not use the relational table model, and they fall into four main families:

Family Data model Typical strength Examples
Document JSON-like documents grouped in collections Flexible, nested records you read and write as a unit MongoDB, Couchbase
Key-value A key that maps to an opaque value Very fast lookups by key, caching, sessions Redis, DynamoDB (also a document store), Memcached
Wide-column Rows with a flexible set of columns grouped in families Huge write volumes spread over many machines Cassandra, HBase
Graph Nodes and relationships Questions about connections ("friends of friends") Neo4j

MongoDB is a document database, and it has features from other families: Redis shows the key-value side, and MongoDB's $graphLookup handles light graph traversal. No family is "better". Each trades something (joins, strict schemas, transaction scope) for something else (flexibility, scale, speed).

MongoDB versus relational databases such as MySQL

A relational database (MySQL, PostgreSQL, SQL Server) stores data in tables with a fixed schema and joins tables with SQL. MongoDB stores documents and lets related data live inside the document. The vocabulary maps closely, which helps if you already know SQL:

SQL (MySQL, PostgreSQL) MongoDB
Database Database
Table Collection
Row Document
Column Field
Primary key _id (always present, unique)
Index Index
JOIN $lookup stage, or (more often) embedding the related data
GROUP BY $group stage
SELECT ... WHERE find(filter, projection)
INSERT, UPDATE, DELETE insertOne, updateOne, deleteOne (and Many)
Transaction Single-document writes are atomic; multi-document transactions are available
Schema (CREATE TABLE) Optional, enforced with schema validation

The practical differences matter more than the vocabulary:

  • Schema: SQL requires you to declare columns first and migrate them. MongoDB lets documents differ, and you can add rules when you want them.
  • Relationships: SQL normalizes data into many tables and joins them. MongoDB encourages embedding data that is read together (an order with its line items in one document), and referencing when data is shared or grows without bound; see Embedding vs Referencing.
  • Scaling out: MongoDB has built-in replication and sharding. Relational databases scale out too, but sharding is usually something you assemble with extra tools.
  • Queries: SQL is a standard language for ad hoc reports across many tables. MongoDB queries are documents, and cross-collection reporting uses the aggregation pipeline.
  • Consistency: both support ACID transactions. In MongoDB, one document is always atomic, so a well-designed document model needs fewer multi-document transactions.

The small translator below shows how simple SQL statements read as MongoDB find calls. It supports only a narrow pattern (a stand-in written for this lesson, not a real SQL engine), but it makes the correspondence concrete.

JS From a SQL SELECT to a MongoDB find

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Feature by feature: RDBMS versus MongoDB

A relational database management system (RDBMS) is built around tables, rows, a declared schema, SQL and strict constraints. Its classic strengths are ACID transactions across any number of tables, referential integrity (foreign keys) and mature tooling for joins and reports. Here is how the main features line up:

Feature RDBMS (MySQL, PostgreSQL) MongoDB
Data model Tables of rows with fixed columns Collections of flexible BSON documents
Schema Declared up front; changes are migrations Flexible by default; optional validation
Relationships Foreign keys and JOIN Embedding, references and $lookup
ACID Transactions across tables are the norm A single document is always atomic; multi-document transactions when needed
Scaling Mostly vertical; read replicas; sharding with extra tooling Built-in replica sets and sharding for horizontal scale
Query language SQL Query documents and the aggregation pipeline
Best at Highly connected data, ad hoc reporting Document-shaped data that changes shape, high write volume

Scalability deserves a closer look because the words are often confused. Vertical scaling means a bigger machine: more CPU, memory and disk. It is simple, but there is a ceiling and a price curve. Horizontal scaling means more machines, each holding part of the data or a copy of it. MongoDB's replica sets add copies for availability and read capacity, and sharding splits the data itself across machines so that both storage and write throughput grow with the cluster.

How MongoDB is organized at run time

A deployment is a hierarchy. A mongod process is the database server: it owns the storage engine (WiredTiger), keeps recently used data in memory and writes a journal for durability. A replica set groups several mongod processes that hold the same data. In a sharded cluster, several replica sets (the shards) are fronted by mongos routers and a set of config servers. Applications talk to MongoDB through a driver over the network; mongosh and Compass are just two more clients. Each piece has a lesson later in this tutorial.

Where MongoDB is used in practice

Teams reach for MongoDB wherever records are naturally documents that vary in shape:

  • E-commerce catalogs. A laptop, a T-shirt and a gift card each have different attributes. One product document holds exactly the fields that product needs, and an order document can carry its line items.
  • Content and websites. Articles, pages and comments with nested blocks and tags map straight to documents, and a new field never needs a table migration.
  • Social and user-generated content. Profiles, feeds and activity streams are written constantly and read as whole objects, which suits sharded document storage.
  • Mobile and web apps. JSON from the front end is stored almost unchanged, so there is little translation code.
  • Internet of Things and event logs. Sensors write huge numbers of small, time-stamped documents; see Capped Collections and the event log project.
  • Healthcare and other record systems. A patient record is a hierarchy of visits, results and notes whose shape differs by case. Such systems also need security and auditing, which MongoDB provides.

Which should you choose?

Choose MongoDB when your data is naturally shaped like documents, the structure changes often, you read and write a record as a whole, or you expect to scale out. Choose a relational database when your data is highly interconnected, you rely on many-table joins and reporting, or strict, enforced structure matters more than flexibility. Many companies use both, each for what it does best. For a MySQL-versus-MongoDB decision specifically, ask: do my queries mostly join many tables (favoring MySQL), or fetch one rich record at a time (favoring MongoDB)?

When to choose MongoDB

MongoDB is a strong fit when:

  • Your data is naturally hierarchical (products with attributes, content with nested blocks, events with varying payloads).
  • Records differ in shape or the model is still changing quickly.
  • You read and write whole objects most of the time, such as a user profile or an order.
  • You need to scale writes horizontally across many machines with sharding (Sharding).

A relational database such as PostgreSQL or MySQL is often the better choice when:

  • Your data is highly interconnected and you query it from many angles with many-table joins.
  • You need strict, enforced structure and constraints everywhere.
  • Your team relies heavily on ad hoc SQL reporting.

This is not a contest with one winner. Modern MongoDB supports multi-document ACID transactions, joins with $lookup, and schema validation, and modern relational databases store JSON columns. Pick based on how your application reads and writes data. Many systems use both.

What you get beyond storage

MongoDB is more than a JSON bucket. Over this tutorial you will use:

  • A rich query language with operators for comparison, logic, arrays and text.
  • Indexes that turn slow collection scans into fast lookups.
  • The aggregation pipeline, a sequence of stages that filters, groups, joins and reshapes data.
  • Replica sets for high availability and sharding for scale.
  • Official drivers for Node.js, Python, Java, C#, Go, PHP and more.

You can install it locally, run it in Docker, or use the hosted service MongoDB Atlas. The next lesson walks through all three.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which pair is the closest match between MongoDB and a relational database?

    A collection groups related documents the way a table groups rows. Unlike rows, documents in one collection can have different fields.
  2. 2. What happens if two documents in the same collection have different sets of fields?

    A collection does not force a fixed field list. You can add validation rules if you want to enforce a shape.
  3. 3. Which situation points towards a document database?

    Whole-object access and varying shapes are the sweet spot, because a document keeps related data together and tolerates different fields.
  4. 4. What are the TryIt blocks in this tutorial running?

    The site cannot start a database server in the browser, so a small JavaScript engine applies MongoDB-style filters, updates and pipelines to arrays of objects.

Summary

  • MongoDB stores documents (JSON-like, stored as BSON) in collections, inside databases.
  • Every document has a unique _id; collections are created on first write.
  • Documents in one collection may differ in shape: a flexible schema, optionally validated.
  • Documents can embed related data, which makes reading and writing one object simple, at the price of some duplication.
  • MongoDB fits hierarchical, varying, whole-object data and horizontal scale; relational databases fit heavily interconnected data. Many teams use both.
  • The TryIts here are JavaScript stand-ins, not a real server.

Next, set up the real thing in Installing MongoDB and Using mongosh.