Tutorial

Working with MongoDB

Tutorial · Databases

Cover: Working with MongoDB

MongoDB stores data as flexible JSON-like documents instead of rows in rigid tables — a shift that changes how you model data, not just the syntax you type.

Documents and collections

{
  "_id": "64f...",
  "name": "Amara",
  "email": "amara@example.com",
  "tags": ["admin", "beta-tester"]
}

A document is one record, stored as BSON (a binary form of JSON). A collection is a group of documents — roughly analogous to a table, except documents in the same collection don't need identical fields.

Basic CRUD

db.users.insertOne({ name: "Kofi", email: "kofi@example.com" })

db.users.find({ name: "Kofi" })

db.users.updateOne(
  { name: "Kofi" },
  { $set: { email: "new-kofi@example.com" } }
)

db.users.deleteOne({ name: "Kofi" })

find takes a query document — the fields to match — rather than a SQL-style WHERE clause. $set is an update operator that changes only the specified fields, leaving the rest of the document untouched.

Querying nested and array fields

db.users.find({ tags: "admin" })          // any user with "admin" in their tags array
db.users.find({ "address.city": "Nairobi" }) // dot notation reaches into nested documents

This is where MongoDB's document model pays off most visibly — related data that would need a JOIN in a relational database can live embedded in one document, if it's read together as often as it's written.

Indexes still matter

db.users.createIndex({ email: 1 })

Without an index, a query scans every document in the collection. An index on frequently-queried fields (email, a lookup key) turns that into a fast lookup — the same tradeoff as in any relational database.

Embed vs. reference. Embed related data directly in a document when it's always read together and rarely updated independently (a blog post's comments). Reference it by ID in a separate collection when it's large, shared across many documents, or updated on its own schedule (a user referenced by many orders). Getting this choice wrong is the most common MongoDB modeling mistake.

Comments