0
0
MongoDBquery~5 mins

How MongoDB stores data as documents

Choose your learning style9 modes available
Introduction

MongoDB stores data as documents to keep information organized in a way that is easy to read and flexible to change.

When you want to save information about a person, like name, age, and address, all together.
When you need to store data that can change often, like a shopping cart with different items.
When you want to keep related data in one place without using many tables.
When you want to quickly add new fields without changing the whole database structure.
Syntax
MongoDB
{ <field1>: <value1>, <field2>: <value2>, ... }
Each document is like a record with fields and values.
Documents are stored in collections, similar to tables in other databases.
Examples
A simple document storing a person's name, age, and city.
MongoDB
{ "name": "Alice", "age": 30, "city": "New York" }
A document representing a product with its price and availability.
MongoDB
{ "product": "Book", "price": 12.99, "inStock": true }
A document with an array field to store multiple hobbies.
MongoDB
{ "name": "Bob", "hobbies": ["reading", "hiking", "coding"] }
Sample Program

This example inserts a document into the 'users' collection and then finds it by name.

MongoDB
db.users.insertOne({ "name": "John", "age": 25, "email": "john@example.com" });
db.users.find({ "name": "John" });
OutputSuccess
Important Notes

Documents in MongoDB are stored in a format called BSON, which is like JSON but supports more data types.

Each document has a unique _id field automatically added if not provided.

Summary

MongoDB stores data as flexible documents with fields and values.

Documents are grouped in collections, making data easy to organize.

This format allows quick changes and storing complex data like arrays and nested objects.