MongoDB Introduction

The document model, when it fits better than relational, and connecting via mongosh.

What MongoDB is

MongoDB is a document-oriented NoSQL database — instead of rows in tables with a fixed schema, it stores documents (JSON-like structures, physically encoded as BSON — Binary JSON) grouped into collections. There's no CREATE TABLE step defining columns up front; a collection simply holds documents, and different documents in the same collection can have different fields entirely.

Javascript
// A document in a "users" collection
{
  _id: ObjectId("65f1a2b3c4d5e6f7a8b9c0d1"),
  name: "Amara Diallo",
  email: "amara@example.com",
  country: "SN",
  interests: ["hiking", "photography"]
}

_id is the document's primary key — MongoDB generates a unique ObjectId automatically if one isn't supplied.

Documents and collections vs. tables and rows

Relational MongoDB
Table Collection
Row Document
Column Field
Primary key _id
JOIN $lookup (aggregation pipeline) or embedding data directly
Fixed schema (enforced by CREATE TABLE) Flexible schema by default (fields can vary per document)

The biggest structural difference isn't the JSON-like syntax — it's that a document can nest arrays and sub-objects directly, so data that would require a join across two or three relational tables can often live inside a single document:

Javascript
// One document holding what would be three joined relational tables
{
  _id: ObjectId("..."),
  title: "Getting started with MongoDB",
  author: "Liam Chen",
  tags: ["mongodb", "databases"],
  comments: [
    { user: "Priya Nair", text: "Great intro!", postedAt: ISODate("2026-02-01") },
    { user: "Amara Diallo", text: "Very helpful, thanks.", postedAt: ISODate("2026-02-02") }
  ]
}

When a document model fits, and when it doesn't

Document modeling tends to fit well when:

  • Data is naturally read and written as a whole unit (a blog post with its comments, a product with its variants and reviews) — one document round-trip instead of several joins.
  • The schema genuinely varies between records (different product categories with wildly different attribute sets) or evolves quickly during early development.
  • The application needs to scale writes horizontally across many machines — MongoDB's sharding model (splitting collections across servers) is a first-class, built-in feature rather than something bolted on.

A relational database tends to fit better when:

  • Data has many-to-many relationships that get queried from multiple directions (an e-commerce system where orders, products, and inventory all need consistent, flexible cross-cutting queries) — this is where JOIN and multi-table transactions genuinely earn their complexity.
  • Strong, immediate consistency and multi-row/multi-table transactional guarantees are essential (financial ledgers, inventory counts that must never go negative under concurrent access).
  • The schema is well understood and stable, and the primary benefit of strict structure (catching bad data at write time) outweighs the flexibility of a loose one.

Modern MongoDB does support multi-document ACID transactions, and modern PostgreSQL supports flexible JSONB columns — the line between the two models has blurred over the years. But the core modeling decision covered on the schema-design page in this section (embed vs. reference) still reflects this same fundamental trade-off: whole-document convenience vs. relational flexibility.

Installing and connecting

MongoDB Community Server installs locally, or you can use a free-tier hosted cluster (MongoDB Atlas) without installing anything. Once installed, connect with mongosh, MongoDB's interactive shell (itself a JavaScript environment):

Bash
mongosh "mongodb://localhost:27017"

Basic navigation, once connected:

Javascript
show dbs
use shop
show collections
db.users.find().limit(5)

use shop switches to (and implicitly creates, on first write) a database named shop. Collections, like databases, don't need to be explicitly created — inserting into db.products.insertOne({...}) creates the products collection automatically if it doesn't already exist.

Common mistakes

  • Treating MongoDB's flexible schema as "no schema needed at all" — a lack of enforced structure doesn't mean the application doesn't have an implicit schema; it just means MongoDB won't catch violations of it for you unless you add validation rules (covered on the schema-design page).
  • Modeling a MongoDB collection exactly like a relational table (one document = one flat row, everything else referenced) and then needing a $lookup for every single query — this throws away the model's main advantage without gaining any of the relational model's guarantees.
  • Assuming MongoDB can't do transactions at all — multi-document ACID transactions have been supported since MongoDB 4.0, though the document model is still designed to minimize how often you need them.