0
0
MongoDBquery~5 mins

Document model mental model (JSON/BSON) in MongoDB

Choose your learning style9 modes available
Introduction

The document model helps you store and organize data in a way that looks like real objects or things you use every day. It uses JSON-like structures to keep data easy to read and flexible.

When you want to store information about people, like their name, age, and address, all in one place.
When you need to save a list of items inside another item, like a shopping cart with many products.
When your data changes often and you want to add new details without changing the whole structure.
When you want to work with data that looks like objects in real life, such as books with authors and reviews.
When you want to quickly find and update parts of your data without complex joins.
Syntax
MongoDB
{
  "key1": "value1",
  "key2": 123,
  "key3": ["item1", "item2"],
  "key4": {
    "subkey1": true
  }
}
Documents are like objects with keys and values, similar to JSON format.
Values can be simple (strings, numbers) or complex (arrays, nested documents).
Examples
A simple document with a name and age.
MongoDB
{ "name": "Alice", "age": 30 }
This document has a list of tags inside it.
MongoDB
{ "product": "Book", "price": 12.99, "tags": ["fiction", "bestseller"] }
Nested document inside the main document.
MongoDB
{ "user": { "firstName": "Bob", "lastName": "Smith" }, "active": true }
Sample Program

This example adds a user document with nested address and hobbies array, then finds it by name.

MongoDB
db.users.insertOne({
  "name": "Emma",
  "age": 28,
  "hobbies": ["reading", "hiking"],
  "address": {
    "street": "123 Maple St",
    "city": "Springfield"
  }
})

// Then find the document
 db.users.find({ "name": "Emma" })
OutputSuccess
Important Notes

MongoDB stores documents in BSON, a binary form of JSON that supports more data types.

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

Documents can be different shapes in the same collection; no fixed schema is required.

Summary

Documents store data as key-value pairs, like JSON objects.

They can include nested documents and arrays for complex data.

This model is flexible and easy to understand, matching real-world objects.