Skip to content

Instantly share code, notes, and snippets.

@powertech2nd
Created March 5, 2026 11:46
Show Gist options
  • Select an option

  • Save powertech2nd/63de09830e48978696dcc5dc070cded6 to your computer and use it in GitHub Desktop.

Select an option

Save powertech2nd/63de09830e48978696dcc5dc070cded6 to your computer and use it in GitHub Desktop.

04 — The NoSQL Superpower: Arrays

Goal: Query data that lives inside a list (array) within a document. Key Idea: MongoDB searches inside arrays automatically — no extra joins needed.


The Problem in SQL

In a relational database, storing multiple tags for a post requires three tables and a join:

Posts table          Post_Tags table        Tags table
──────────────       ───────────────        ──────────
id | title           post_id | tag_id       id | name
───────────          ─────────────────      ──────────
 1 | "Hello"            1    |   42          42 | "Tutorial"
SELECT Posts.*
FROM Posts
JOIN Post_Tags ON Posts.id = Post_Tags.post_id
JOIN Tags ON Post_Tags.tag_id = Tags.id
WHERE Tags.name = 'Tutorial';

The MongoDB Way

A post document simply contains its tags as an array:

{
  "_id": 1,
  "title": "Hello World",
  "tags": ["Tutorial", "Beginner", "JavaScript"]
}

To find all posts tagged "Tutorial":

db.posts.find({ tags: "Tutorial" });

That's it. MongoDB checks inside the array automatically.


🔍 How Array Matching Works

// Document in DB:
{ tags: ["Tutorial", "Beginner", "JavaScript"] }

// Query:
db.posts.find({ tags: "Tutorial" })
// MongoDB asks: "Is 'Tutorial' anywhere in the tags array?"
// Answer: YES → document is returned ✅

More Array Operators

Match documents where array contains ALL of these values

db.posts.find({ tags: { $all: ["Tutorial", "JavaScript"] } });

Match documents where array contains ANY of these values

db.posts.find({ tags: { $in: ["Tutorial", "Beginner"] } });

Match documents where array has exactly N elements

db.posts.find({ tags: { $size: 3 } });

Query inside an array of objects

// Document:
{ "comments": [ { "author": "Alice", "likes": 10 }, ... ] }

// Find posts where any comment has more than 5 likes:
db.posts.find({ "comments.likes": { $gt: 5 } });

SQL vs. MongoDB: Side by Side

Task SQL MongoDB
Store multiple tags Separate join table Array field in document
Find by one tag 2–3 table JOIN { tags: "value" }
Find by multiple tags Complex JOIN + WHERE IN { tags: { $all: [...] } }

💡 Notes

  • Arrays are one of the biggest advantages of document databases.
  • This is why MongoDB is often a better fit for data with one-to-many relationships (posts → tags, users → addresses, orders → items).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment