Skip to main content

Documents

MongoDB is a NoSQL database type that stores data in a format known as BSON, which is a binary representation of JSON-like documents. These documents are grouped together into collections, forming the core of MongoDB's structure.

Understanding MongoDB Documents

A MongoDB document is a data structure composed of field and value pairs. In simple terms, they are similar to JSON objects or Python dictionaries. The values of fields can include other documents, arrays, and arrays of documents.

Here is an example of a MongoDB document:

{
"name": "John Doe",
"age": 25,
"address": {
"street": "123 Main St",
"city": "Springfield",
"zip": "12345"
},
"hobbies": ["reading", "cycling", "hiking"]
}

In this document, name, age, address, and hobbies are fields. Each field has a value. The address field is a subdocument, and the hobbies field is an array of strings.

Field Names

Field names are case-sensitive, must be unique within a document, and cannot contain null characters. The . and $ characters have special properties and must be used with care.

MongoDB Document Size Limit

There is a maximum limit to the size of a document in MongoDB. As of MongoDB version 4.0, a single document in a collection, including all embedded documents, must be less than or equal to 16 megabytes.

Document Structure

In MongoDB, documents in the same collection do not need to have the same structure. For example, the following two documents could exist in the same collection:

{
"name": "John Doe",
"age": 25
}
{
"first_name": "Jane",
"last_name": "Doe",
"email": "[email protected]"
}

While this can provide flexibility, it's generally a good practice to ensure documents in a collection have a similar or consistent structure.

Unique Identifier or _id Field

Every MongoDB document is automatically given an _id field if not provided. This _id field serves as a primary key for the document and ensures its uniqueness within a collection. By default, this is a ObjectId that is generated at the time of insertion. You can also provide a custom value for _id as long as it is unique within the collection.

{
"_id": ObjectId("5099803df3f4948bd2f98391"),
"name": "John Doe",
"age": 25
}

Understanding MongoDB documents is crucial as they form the primary unit of data in MongoDB. They offer flexible and varied data structures, allowing you to handle data in ways that align closely with how data is handled in most programming languages.

In the next section, we will delve deeper into how to perform operations on MongoDB documents – creating, reading, updating, and deleting (CRUD operations).