Understanding MongoDB Documents: A Key to NoSQL Data Modeling
Learn about the fundamental concept of documents in MongoDB, which are analogous to rows in relational databases. Explore the structure of MongoDB documents, including fields and their JSON representation. This guide will provide you with a clear understanding of how documents are used to store and organize data in MongoDB.
In MongoDB, a document is akin to a row in a traditional RDBMS table, and a collection is similar to a table. Each document is represented in JSON format and consists of fields (like columns in RDBMS tables).
Example of a MongoDB Document
A MongoDB document is contained within curly braces and follows the "field":"value"
format. Fields are separated by commas:
MongoDB Document
{
"_id": ObjectId("32521df3f4948bd2f54218"),
"firstName": "John",
"lastName": "King",
"email": "john.king@abc.com",
"salary": "33000",
"DoB": new Date('Mar 24, 2011'),
"skills": [ "Angular", "React", "MongoDB" ],
"address": {
"street":"Upper Street",
"house":"No 1",
"city":"New York",
"country":"USA"
}
}
The document above includes:
_id
: Unique identifier (ObjectId).skills
: An array containing skill names.address
: An embedded document with address details.
JSON vs BSON
MongoDB stores data as BSON (Binary JSON), which extends JSON with additional data types. BSON documents are converted from JSON for internal storage and retrieval.
Important Points:
- Field names can be used without quotes if they do not contain spaces, e.g.,
{ name: "Steve" }
. - Embedded documents can be accessed using dot notation, e.g.,
address.phone.number
. - Document size limit: 16 MB. Use GridFS for larger documents.
- Fields in BSON documents are ordered. For example,
{x: 1, y: 2}
is not the same as{y: 2, x: 1}
. - MongoDB collections do not enforce schemas, so documents in a collection can have different fields.
Embedded Documents
An embedded document is a document within another document. Here’s an example:
Embedded Document
{
"_id": ObjectId("32521df3f4948bd2f54218"),
"firstName": "John",
"lastName": "King",
"department": {
"_id": ObjectId("55214df3f4948bd2f8753"),
"name":"Finance"
},
"address": {
"phone": { "type": "Home", "number": "111-000-000" }
}
}
In this document:
department
: An embedded document with department details.address.phone
: An embedded document within the address field.
Arrays in MongoDB Documents
Fields in documents can contain arrays, which may include any data type or embedded documents. Access array elements using dot notation with zero-based indexing:
Document with an Array
{
"_id": ObjectId("32521df3f4948bd2f54218"),
"firstName": "John",
"lastName": "King",
"email": "john.king@abc.com",
"skills": [ "Angular", "React", "MongoDB" ]
}
In the example, skills
is an array of strings. To access the second element, use skills.1
.