# MongoDB: A Practical Guide to Thinking in Documents

Think about how your application already holds an order in memory. It is one object: a customer, a delivery address, a list of items, a status. To save it in a relational database you split it across four or five tables, and to load it again you join them back together.

MongoDB asks a simple question: what if you just saved the object?

That idea made MongoDB the best-known document database. It also led plenty of teams into trouble, because "no fixed schema" is easy to mistake for "no design needed". This guide shows how to get the benefits without the trouble.

## What MongoDB is

MongoDB is a document database. Instead of rows in tables, it stores **documents** in **collections**. A document is a JSON-like record (stored in a binary format called BSON) that can contain nested objects and arrays:

```javascript
{
  _id: ObjectId("665f1c2e9b1e8a3f4c2d1a7b"),
  customer: { id: 42, name: "Asha Rao" },
  items: [
    { sku: "CONE-01", qty: 2, price: 3.5 },
    { sku: "TUB-09", qty: 1, price: 7.0 }
  ],
  status: "paid",
  createdAt: ISODate("2026-03-01T10:15:00Z")
}
```

Every document has an `_id`, its primary key. Documents in the same collection do not have to share the same fields.

MongoDB is developed by MongoDB, Inc. The Community Edition is free to use and its source is available under the Server Side Public License (SSPL), which places conditions on companies that offer MongoDB itself as a service. The company's hosted service is called Atlas.

## Why teams choose it

### Data shaped like your code

A document maps directly to an object or a dictionary in your programming language. There is less translation between the application and the database, and things you read together are stored together, so one read fetches the whole order.

### The schema can change as you go

Adding a field does not need a migration. New documents simply include it. That suits products whose data model is still moving, and data that naturally varies, such as product catalogues where a shirt and a laptop have different attributes.

### High availability is standard

A production MongoDB deployment is a **replica set**: usually three servers holding the same data. If the primary fails, the others elect a new one automatically, typically within seconds.

### It can spread across machines

**Sharding** splits a collection across several servers by a key you choose. It is built in, and it is how MongoDB handles data sets too large for one machine.

## Where MongoDB fits, and where it does not

**A strong choice for:**

- Content, catalogues and user profiles with varied structure
- Event and activity data
- Applications where a whole record is usually read and written at once
- Fast-moving products that have not settled their data model
- Mobile and web backends that work mostly with JSON

**Look elsewhere when:**

- **Your data is highly relational.** If most questions need joins across many entities, such as accounting or inventory with many cross-references, a relational database such as PostgreSQL will be simpler and safer.
- **Many operations must change several records atomically.** MongoDB has multi-document transactions, but if you need them on most operations, you are working against its design.
- **You rely on ad hoc reporting with SQL.** Analysts and reporting tools speak SQL first.
- **You want the database to enforce every rule.** MongoDB has no foreign keys. Relationships are your application's responsibility.

## Using it the right way

The examples below use `mongosh`, the MongoDB shell.

```bash
mongosh "mongodb://localhost:27017/shop"
```

### Design around your queries

In a relational database you model the data, then write queries. In MongoDB you list the questions your application asks, then shape documents to answer them. The central decision is whether to **embed** related data or **reference** it.

| Embed it when | Reference it when |
|---|---|
| It is read together with the parent | It is read on its own |
| It belongs to one parent only | It is shared by many parents |
| The list has a small, known upper size | The list can grow without limit |
| It rarely changes | It changes often and independently |

Order items belong inside the order. A customer's ten thousand orders do not belong inside the customer: store the customer's id on each order instead. A single document is limited to 16 MB, and long before that limit, a huge document is slow to load and rewrite.

### Read and write

```javascript
db.orders.insertOne({
  customer: { id: 42, name: "Asha Rao" },
  items: [{ sku: "CONE-01", qty: 2, price: 3.5 }],
  status: "paid",
  createdAt: new Date()
})

// A customer's latest orders, selected fields only
db.orders.find(
  { "customer.id": 42, status: "paid" },
  { items: 1, createdAt: 1 }
).sort({ createdAt: -1 }).limit(20)

// Change one field without rewriting the document
db.orders.updateOne(
  { _id: ObjectId("665f1c2e9b1e8a3f4c2d1a7b") },
  { $set: { status: "shipped" }, $currentDate: { updatedAt: true } }
)
```

Always update with operators such as `$set`, `$inc` and `$push`. They change just the named fields, and they are safe when two clients update at once.

### Index what you query

Without an index, MongoDB reads every document in the collection, which it calls a collection scan.

```javascript
db.orders.createIndex({ "customer.id": 1, status: 1, createdAt: -1 })
```

For an index on several fields, a good rule of thumb is ESR: fields you match **E**xactly first, then the field you **S**ort by, then fields you filter by **R**ange.

Check that a query uses the index:

```javascript
db.orders.find({ "customer.id": 42, status: "paid" })
  .sort({ createdAt: -1 })
  .explain("executionStats")
```

In the output, `IXSCAN` means an index was used and `COLLSCAN` means it was not. Compare `totalDocsExamined` with `nReturned`: if the database examined a hundred thousand documents to return twenty, the index is wrong.

### Report with the aggregation pipeline

An aggregation pipeline passes documents through a series of stages, like commands joined by pipes in a shell.

```javascript
db.orders.aggregate([
  { $match: { status: "paid" } },
  { $unwind: "$items" },
  { $group: {
      _id: "$items.sku",
      units: { $sum: "$items.qty" },
      revenue: { $sum: { $multiply: ["$items.qty", "$items.price"] } }
  } },
  { $sort: { revenue: -1 } },
  { $limit: 5 }
])
```

That finds the five best-selling products. Put `$match` first so later stages work on as few documents as possible, and so an index can be used.

### Add rules where they matter

Flexible does not have to mean anything goes. A validator rejects documents that break your rules:

```javascript
db.runCommand({
  collMod: "orders",
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["customer", "items", "status", "createdAt"],
      properties: {
        status: { enum: ["pending", "paid", "shipped", "cancelled"] },
        items: { bsonType: "array", minItems: 1 }
      }
    }
  }
})
```

### Decide how safe a write must be

On a replica set, a **write concern** says how many servers must confirm a write before it counts. `{ w: "majority" }` means a majority of the set has the data, so it survives the loss of a server. It is the default on current versions. Lower it only for data you can afford to lose.

### Lock it down and back it up

Turn on authentication and give each application its own user:

```javascript
use shop
db.createUser({
  user: "shop_app",
  pwd: passwordPrompt(),
  roles: [{ role: "readWrite", db: "shop" }]
})
```

Do not expose a MongoDB port to the open internet without authentication and a firewall. For backups, `mongodump` and `mongorestore` suit smaller databases:

```bash
mongodump --uri="mongodb://localhost:27017/shop" --gzip --archive=shop.archive
mongorestore --uri="mongodb://localhost:27017" --gzip --archive=shop.archive
```

Larger deployments use file system snapshots or the managed backup of a hosted service.

## Common mistakes

- **Arrays that grow forever.** Comments on a popular post, or events on a device, pushed into one document. The document gets slower with every write and can hit the size limit. Move the items to their own collection.
- **No indexes, or one index per field.** Build indexes that match whole queries, and remove ones that are never used.
- **Rebuilding joins with `$lookup` everywhere.** An occasional `$lookup` is fine. If every query needs several, the data wants to be relational.
- **Inconsistent types.** One document stores a price as a number, another as a string. Queries and sorts then silently miss records. Schema validation prevents this.
- **Floating point money.** Store money as whole cents in an integer, or use the `Decimal128` type.
- **Running a single server in production.** No failover, and no transactions. Use a replica set.
- **Choosing a shard key casually.** A key that only ever increases sends all new writes to one shard. Choose a key that spreads writes and appears in your common queries, and take your time over it.
- **Reading whole documents for one field.** Use a projection to return only what you need.

## Quick reference

| Task | Command in `mongosh` |
|---|---|
| List databases | `show dbs` |
| Switch database | `use shop` |
| List collections | `show collections` |
| Count matching documents | `db.orders.countDocuments({ status: "paid" })` |
| One sample document | `db.orders.findOne()` |
| List indexes | `db.orders.getIndexes()` |
| Collection statistics | `db.orders.stats()` |
| Running operations | `db.currentOp()` |
| Stop an operation | `db.killOp(opid)` |
| Replica set health | `rs.status()` |

MongoDB works best when you treat the schema as something you design deliberately, in the application and with validators, instead of something you no longer need. Do that, index for your queries, and it is a pleasant database to build on.

## Exploring MongoDB with CreamDB

The shell is precise, but nested documents are easier to read on a screen built for them. [CreamDB](https://www.creamdb.com) has a MongoDB explorer that runs in your browser, with nothing to install.

- Browse databases and collections, with document counts and sizes.
- Find documents with a filter, projection and sort, and page through the results.
- Run aggregation pipelines and see the output.
- Check a collection's indexes and statistics.
- Ask in plain English, for example "top five products by revenue this month", and the assistant writes the query or pipeline and shows the result.

The assistant reads on its own. Inserting, changing or deleting documents waits as an approval card that you answer, and read-only mode on the server refuses every write. Both `mongodb://` and `mongodb+srv://` connection strings work. CreamDB is a hosted service, so the server has to be reachable from the internet, as an Atlas cluster is.

The same tab also holds your SQL databases, so you can keep MongoDB and PostgreSQL side by side. It is free to start.

