Bird
Raised Fist0
MongoDBquery~5 mins

Why document databases over relational in MongoDB

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction

Document databases store data in flexible, easy-to-understand formats. They let you work with data that changes often or has many parts without strict rules.

When your data has many different fields that can change over time.
When you want to store related information together in one place, like a user and their orders.
When you need to build apps quickly without designing complex tables.
When your data structure is not fixed and can vary between records.
When you want to scale your database easily across many servers.
Syntax
MongoDB
db.collection.insertOne({ key: value, key2: value2, ... })
Documents are stored in collections, similar to tables in relational databases.
Each document is a JSON-like object, which can have nested objects and arrays.
Examples
Insert a user document with name, age, and a list of hobbies.
MongoDB
db.users.insertOne({ name: "Alice", age: 30, hobbies: ["reading", "hiking"] })
Store an order with multiple items inside one document.
MongoDB
db.orders.insertOne({ orderId: 123, items: [{ product: "Book", qty: 2 }, { product: "Pen", qty: 5 }] })
Sample Program

This example creates a product document in the 'products' collection and then retrieves it to show the stored data.

MongoDB
use shopDB

db.products.insertOne({ name: "Coffee Mug", price: 12.99, tags: ["kitchen", "drinkware"], stock: 100 })

const product = db.products.findOne({ name: "Coffee Mug" })
printjson(product)
OutputSuccess
Important Notes

Document databases are great for flexible and evolving data but may not enforce strict relationships like relational databases.

They often provide faster reads and writes for certain types of data because they avoid complex joins.

Summary

Document databases store data as flexible JSON-like documents.

They are useful when data structure changes or is complex.

They simplify storing related data together and scaling databases.

Practice

(1/5)
1. Why might someone choose a document database like MongoDB over a traditional relational database?
easy
A. Because document databases store data in flexible JSON-like documents that can change structure easily.
B. Because document databases require fixed schemas and strict table relations.
C. Because document databases only work with numeric data.
D. Because document databases do not support indexing.

Solution

  1. Step 1: Understand data storage formats

    Document databases store data as JSON-like documents, allowing flexible and dynamic structures.
  2. Step 2: Compare with relational databases

    Relational databases require fixed schemas and tables, making changes harder.
  3. Final Answer:

    Because document databases store data in flexible JSON-like documents that can change structure easily. -> Option A
  4. Quick Check:

    Flexible JSON-like storage [OK]
Hint: Flexible JSON documents mean easier schema changes [OK]
Common Mistakes:
  • Thinking document DBs require fixed schemas
  • Believing document DBs only handle numbers
  • Assuming no indexing in document DBs
2. Which of the following is the correct way to insert a document into a MongoDB collection named users?
easy
A. insert document into users {name: 'Alice', age: 30}
B. INSERT INTO users VALUES ('Alice', 30)
C. db.users.insertOne({name: 'Alice', age: 30})
D. db.users.add({name: 'Alice', age: 30})

Solution

  1. Step 1: Recall MongoDB insert syntax

    MongoDB uses insertOne() to add a single document to a collection.
  2. Step 2: Check options for correct syntax

    db.users.insertOne({name: 'Alice', age: 30}) uses db.users.insertOne({name: 'Alice', age: 30}), which is correct MongoDB syntax.
  3. Final Answer:

    db.users.insertOne({name: 'Alice', age: 30}) -> Option C
  4. Quick Check:

    MongoDB insertOne() [OK]
Hint: MongoDB uses insertOne() for single document inserts [OK]
Common Mistakes:
  • Using SQL syntax in MongoDB
  • Using non-existent methods like add()
  • Writing commands as plain English
3. Given the following MongoDB document stored in the products collection:
{ "_id": 1, "name": "Pen", "details": { "color": "blue", "price": 1.5 } }

What will the query db.products.find({"details.color": "blue"}) return?
medium
A. All products with a details field containing color blue.
B. Only products with a top-level field named color equal to blue.
C. An error because nested fields cannot be queried.
D. No results because the query syntax is wrong.

Solution

  1. Step 1: Understand dot notation in queries

    MongoDB allows querying nested fields using dot notation like "details.color".
  2. Step 2: Analyze the query and document

    The document has a nested field details.color with value "blue", so the query matches this document.
  3. Final Answer:

    All products with a details field containing color blue. -> Option A
  4. Quick Check:

    Dot notation queries nested fields [OK]
Hint: Use dot notation to query nested document fields [OK]
Common Mistakes:
  • Thinking nested fields can't be queried
  • Confusing top-level and nested fields
  • Assuming query syntax is SQL-like
4. You wrote this MongoDB query to find users aged over 25:
db.users.find({age: > 25})

Why does this query fail and how to fix it?
medium
A. Use SQL syntax: SELECT * FROM users WHERE age > 25.
B. The query is correct; failure is due to missing collection.
C. Replace > with >= for correct MongoDB syntax.
D. The operator > should be inside $gt like {age: {$gt: 25}}.

Solution

  1. Step 1: Identify MongoDB comparison operator syntax

    MongoDB uses special operators like $gt for 'greater than' inside query objects.
  2. Step 2: Correct the query syntax

    The correct query is {age: {$gt: 25}}, not using > directly.
  3. Final Answer:

    The operator > should be inside $gt like {age: {$gt: 25}}. -> Option D
  4. Quick Check:

    Use $gt for greater than in MongoDB queries [OK]
Hint: Use $gt, $lt for comparisons, not > or < directly [OK]
Common Mistakes:
  • Using > directly in query object
  • Mixing SQL syntax with MongoDB
  • Assuming >= fixes the error
5. You have a blog application storing posts and comments. Why is a document database better than a relational one for storing posts with many comments?
hard
A. Because relational databases cannot store comments at all.
B. Because you can store each post and its comments together in one document, making reads faster.
C. Because document databases require all comments to be in separate collections.
D. Because relational databases do not support indexing on comments.

Solution

  1. Step 1: Understand data embedding in document databases

    Document databases allow embedding related data (like comments) inside a single document (post).
  2. Step 2: Compare with relational approach

    Relational databases store posts and comments in separate tables, requiring joins to combine them.
  3. Step 3: Benefits of embedding

    Embedding comments inside posts reduces the need for joins and speeds up reading a post with its comments.
  4. Final Answer:

    Because you can store each post and its comments together in one document, making reads faster. -> Option B
  5. Quick Check:

    Embedding related data = faster reads [OK]
Hint: Embed related data in one document for faster access [OK]
Common Mistakes:
  • Thinking relational DBs can't store comments
  • Believing comments must be separate collections
  • Assuming relational DBs lack indexing