Lesson 8 of 50 – Documents and BSON in MongoDB
16%

Documents and BSON in MongoDB

MongoDB stores data as documents inside collections. Documents contain field-value pairs and use a structure similar to JSON. MongoDB stores documents internally using BSON, which supports additional data types such as dates, ObjectIds, and binary data.

1. What Is a Document in MongoDB?

A document is a basic unit of data in MongoDB. It contains fields and their corresponding values.

Example of a student document:

{
    "student_id": 101,
    "name": "Rahul",
    "age": 20,
    "course": "ADCA",
    "city": "Aurangabad"
}

In this example:

  • student_id is a field.
  • 101 is its value.
  • name is a field.
  • "Rahul" is its value.
  • The complete structure is one document.

Documents are similar to records in a relational database, although their structure and data model are different.

2. What Is BSON?

BSON stands for Binary JSON. It is a binary-encoded serialization format used by MongoDB to represent documents.

BSON is designed to support efficient document processing and data types beyond those available in standard JSON.

Some BSON data types include:

  • String
  • Double
  • Integer
  • Boolean
  • Date
  • ObjectId
  • Array
  • Embedded document
  • Binary data
  • Decimal128
Remember: JSON is a text-based data format. BSON is a binary-encoded format that supports additional types and is used for MongoDB document storage and exchange.

3. JSON vs BSON

JSON BSON
Text-based format Binary-encoded format
Commonly used for data exchange Used by MongoDB to represent documents
Has a limited set of built-in data types Supports additional types such as ObjectId and Date
Easy to read as plain text Not generally intended to be read as plain text
Does not have a native date type Supports a dedicated date type

MongoDB Shell and Compass commonly display documents in a readable JSON-like representation, even though MongoDB uses BSON internally.

4. Fields and Values

Each document contains fields. A field has a name and an associated value.

{
    "name": "Amit",
    "age": 22,
    "isActive": true,
    "feesPaid": 5000
}

Explanation:

  • name has a string value.
  • age has a numeric value.
  • isActive has a Boolean value.
  • feesPaid has a numeric value.

Field names are strings. In MongoDB Shell examples, field names are commonly written without quotation marks when valid JavaScript identifiers, or with quotation marks when using JSON-style syntax.

5. Common BSON Data Types

1. String
{
    name: "Rahul"
}

Stores text.


2. Number
{
    age: 20,
    percentage: 85.5
}

MongoDB supports numeric BSON types such as 32-bit integers, 64-bit integers, doubles, and Decimal128. The type used depends on how the value is represented and inserted.


3. Boolean
{
    isActive: true,
    isPaid: false
}

Stores either true or false.


4. ObjectId
{
    _id: ObjectId("507f1f77bcf86cd799439011")
}

ObjectId is commonly used as MongoDB's automatically generated identifier for documents.


5. Date
{
    admissionDate: ISODate("2026-01-15T00:00:00Z")
}

The BSON Date type stores a date and time as milliseconds since the Unix epoch. MongoDB Shell commonly displays dates using ISODate() notation.


6. Array
{
    skills: ["HTML", "CSS", "JavaScript"]
}

An array stores an ordered list of values.


7. Embedded Document
{
    name: "Priya",
    address: {
        city: "Patna",
        state: "Bihar"
    }
}

An embedded document stores another document inside the main document.

6. The _id Field

Every standard MongoDB document in a collection has an _id field that uniquely identifies that document within its collection.

Example:

{
    _id: ObjectId("507f1f77bcf86cd799439011"),
    name: "Rahul",
    course: "ADCA"
}

Important points:

  • MongoDB automatically generates an ObjectId for _id when one is not supplied.
  • You can provide your own unique value for _id.
  • The _id value cannot be changed after the document is inserted.
  • The default unique index on _id prevents duplicate identifier values in a collection.

7. Nested Documents

MongoDB allows you to store a document inside another document. This is called an embedded or nested document.

Example:

{
    name: "Amit Kumar",
    course: "Web Development",
    address: {
        village: "Rampur",
        district: "Aurangabad",
        state: "Bihar"
    }
}

To query a nested field, use dot notation in quotation marks.

db.students.find({
    "address.district": "Aurangabad"
})

This query finds student documents whose nested address.district field equals "Aurangabad".

8. Insert Documents with Different Data Types

The following example inserts a document containing strings, numbers, a Boolean, an array, a nested document, and a date.

db.students.insertOne({
    name: "Rahul",
    age: 20,
    percentage: 85.5,
    isActive: true,
    skills: ["HTML", "CSS", "JavaScript"],
    address: {
        city: "Aurangabad",
        state: "Bihar"
    },
    admissionDate: new Date("2026-01-15")
})

Retrieve the document:

db.students.find()

MongoDB stores the date as a BSON Date value and the array and nested object as their corresponding BSON structures.

9. Complete Practical Example

Create a database for a training institute and insert a document containing different data types.

Step 1: Select the database

use soopro_db

Step 2: Insert a course document

db.courses.insertOne({
    courseName: "Web Development",
    durationMonths: 6,
    fee: 10000,
    isAvailable: true,
    topics: ["HTML", "CSS", "JavaScript"],
    trainer: {
        name: "Amit",
        city: "Patna"
    },
    createdAt: new Date()
})

Step 3: Display the document

db.courses.find()

Step 4: Find courses with a fee of 10000

db.courses.find({
    fee: 10000
})

This example demonstrates how MongoDB documents can represent different data types in a single record.

10. Practice Assignment

  1. Explain what a MongoDB document is.
  2. Write the full form of BSON.
  3. List five BSON data types.
  4. Write a document for an employee containing name, age, and salary.
  5. Add an array of skills to the employee document.
  6. Add a nested address document.
  7. Insert the document into an employees collection.
  8. Explain the purpose of the _id field.
  9. Write a query to find employees from Patna using a nested address field.

🧠 Quick Quiz

Q1. What is the full form of BSON?




Q2. Which field is used as the default document identifier?




Q3. Which BSON type is suitable for storing a date and time?