Goal: Query data that lives inside a list (array) within a document. Key Idea: MongoDB searches inside arrays automatically — no extra joins needed.
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';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.
// 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 ✅db.posts.find({ tags: { $all: ["Tutorial", "JavaScript"] } });db.posts.find({ tags: { $in: ["Tutorial", "Beginner"] } });db.posts.find({ tags: { $size: 3 } });// Document:
{ "comments": [ { "author": "Alice", "likes": 10 }, ... ] }
// Find posts where any comment has more than 5 likes:
db.posts.find({ "comments.likes": { $gt: 5 } });| 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: [...] } } |
- 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).