๐Ÿƒ MongoDB Guide

A beginner-friendly guide to the leading NoSQL document database โ€” from install to your first CRUD operations

1. What is MongoDB?

MongoDB is a popular NoSQL document database. Instead of storing data in rows and columns like PostgreSQL, it stores data as documents โ€” self-contained JSON-like records grouped into collections. Each document can hold its own structure, which makes MongoDB flexible for data that changes shape.

๐Ÿ“ฆ Analogy โ€” Folders of Envelopes vs a Spreadsheet
A relational database is a giant spreadsheet: every row must have the same columns. MongoDB is a filing cabinet where each envelope (document) can contain whatever fits โ€” one order with a discount, another without, one shipment with three items, another with five. You don't have to invent empty columns just because most envelopes don't use them.

๐ŸŽฏ Real-World Examples

ScenarioWhy MongoDB
Content & CMSBlog posts and articles naturally vary in structure
IoT & sensor dataFlexible schemas ingest many device shapes
CatalogsProducts with optional attributes โ€” no sparse-column pain
Real-time analyticsAggregation pipelines power instant dashboards

2. Why use MongoDB? (The Benefits)

๐Ÿชถ Flexible schema
Documents can differ between records โ€” evolve your data model without migrations.
๐Ÿง‘โ€๐Ÿ’ป Dev-friendly JSON
Easily maps to objects in JavaScript, Python, and most programming languages.
๐Ÿ“ˆ Horizontal scaling
Splits data across servers (sharding) as you grow.
โšก Fast iteration
No table definitions to manage โ€” just insert and go.
๐Ÿ”Ž Rich query language
Range, arrays, geospatial, and text search built in.
โ˜๏ธ Managed cloud
MongoDB Atlas offers a free tier โ€” zero infrastructure to run.

3. MongoDB vs PostgreSQL (Quick Example)

Let's store the same little "product" two ways to see the thinking differ.

๐Ÿ—ƒ๏ธ Relational (PostgreSQL) โ€” fixed columns

CREATE TABLE products (
      id SERIAL PRIMARY KEY,
      name TEXT,
      price NUMERIC,
      color TEXT,
      size TEXT   -- all rows share all columns
  );
INSERT INTO products (name, price, color, size) VALUES ('T-shirt', 20, 'blue', 'M');

๐Ÿƒ Document (MongoDB) โ€” self-contained docs

db.products.insertOne({
      name: "T-shirt",
      price: 20,
      details: { color: "blue", size: "M" }
  });
// another product can have totally different fields
db.products.insertOne({ name: "Hat", price: 12 });
โš–๏ธ Analogy โ€” Forms vs Free-Form Notes
Relational is a government form: the fields exist even when you leave them blank. MongoDB is free-form notes: you only write the fields you have. Both store information โ€” they just model it differently, and different apps prefer different styles.

4. Core Concepts

TermWhat it is
DatabaseA named container for collections
CollectionA group of documents (roughly a "table")
DocumentA single JSON-like record (roughly a "row")
FieldA key/value pair inside a document (roughly a "column")
_idThe unique primary key MongoDB adds automatically to every document
Embedded doc / arrayNested objects inside a document โ€” denormalized but fast
Aggregation pipelineChained stages ($match, $group) that transform data

5. Install MongoDB

Install on Linux (Ubuntu/Debian via apt)

MongoDB community self-licence repo. Add the official package repository, then:

$ sudo apt update
$ sudo apt install -y mongodb-org
$ sudo systemctl enable --now mongod
$ systemctl status mongod
Install on Windows

Run the MSI installer from mongodb.com/try/download/community. Check Install MongoDB as a Service โ€” then MongoDB starts automatically.

> net start MongoDB
Or run via Docker (works everywhere)
$ docker run -d --name mongo -p 27017:27017 mongo

Published to port 27017 โ€” the default Mongo server port.

6. Hands-on: Your First CRUD

๐Ÿงช A short session with mongosh

$ mongosh

// Create โ€” insert a document
db.products.insertOne({ name: "Keyboard", price: 45 });

// Read โ€” find everything (pretty-printed)
db.products.find().pretty()

// Read with a filter (matches the field)
db.products.find({ name: "Keyboard" })

// Update โ€” set a field
db.products.updateOne(
      { name: "Keyboard" },
      { $set: { price: 49 } }
  );

// Delete โ€” remove matches
db.products.deleteOne({ name: "Keyboard" });

mongosh is the modern MongoDB shell โ€” type db to confirm you're connected.

7. Quick Reference

CommandWhat it does
db.collection.insertOne({...})Insert one document
db.collection.find({})Query documents
db.collection.updateOne(filter, {$set:{...}})Update first matching doc
db.collection.deleteOne(filter)Delete first matching doc
db.collection.aggregate([...])Chained transform pipeline
show dbsList databases
use <db>Switch/select a database
show collectionsList collections in current db

8. Best Practices & Next Steps

๐Ÿ” Index first
Put indexes on fields your queries filter frequently.
๐Ÿ“ฆ Embed, don't normalize everything
Embed arrays/objects you always read TOGETHER; store large shared data separately.
๐Ÿ›ก Use schema validation
Flexible doesn't mean messy โ€” add validation where it matters.
๐Ÿ” Enable auth
On real deployments, create users and enforce TLS; don't expose on a open network.
๐Ÿ’พ Back up
mongodump / mongorestore for one-off copies; Atlas has built-in backups.
๐Ÿงญ Go deeper
Next: indexes, aggregation pipelines, geospatial, replica sets, and MongoDB Atlas.

MongoDB trades rigid structure for flexibility โ€” when your data grows, your documents grow with it.
Install it, insert a document, run a query, and you've met the most popular NoSQL store.

Created by jcmatira