0
0
MongoDBquery~5 mins

Why document databases over relational in MongoDB

Choose your learning style9 modes available
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.