Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Understanding Documents

Understanding documents in MongoDB

Documents are the basic unit of data in MongoDB. A document is a record in a MongoDB collection and is represented as a JSON-like structure called BSON (Binary JSON). Each document contains one or more fields, and each field contains a value of a specific data type.

Structure of a Document

Below is an example of a typical document structure in MongoDB:

Document Example

{
    "_id": ObjectId("507f1f77bcf86cd799439011"),
    "name": "Alice",
    "age": 25,
    "email": "alice@example.com",
    "address": {
        "street": "123 Main St",
        "city": "Springfield",
        "state": "IL",
        "zip": "62704"
    },
    "phoneNumbers": [
        {
            "type": "home",
            "number": "555-555-5555"
        },
        {
            "type": "work",
            "number": "555-555-5556"
        }
    ],
    "dateOfBirth": ISODate("1995-01-15T00:00:00Z")
}

Key Features of Documents

Some key features of documents in MongoDB include:

  • Dynamic Schema: Documents can have different sets of fields, making the schema flexible.
  • Embedded Documents: Documents can contain nested documents, allowing for complex data structures.
  • Data Types: Documents support a variety of data types including strings, numbers, arrays, and binary data.

Example: Employee Document

Below is an example of an employee document in MongoDB:

Employee Document

{
    "_id": ObjectId("507f191e810c19729de860ea"),
    "firstName": "John",
    "lastName": "Doe",
    "position": "Software Engineer",
    "salary": 90000,
    "department": "Engineering",
    "projects": [
        {
            "name": "Project A",
            "deadline": ISODate("2022-12-31T00:00:00Z")
        },
        {
            "name": "Project B",
            "deadline": ISODate("2023-03-31T00:00:00Z")
        }
    ]
}