Day 3: NoSQL Data Types in MongoDB
Introduction
MongoDB is one of the most popular NoSQL databases that follows the document model. It stands out for its flexibility in handling unstructured or semi-structured data, thanks to the diverse data types it supports. In this article, we will explore the main data types in MongoDB and how they are used.
Basic Data Types in MongoDB
1. String
The primary type for storing textual data, used for names, addresses, and other text-based information.
example:
{ "name": "John Doe",
"email": "john@example.com" }
2. Numbers
MongoDB supports several numeric types:
- Integer: For whole numbers (32-bit or 64-bit)
- Double: For decimal numbers
- Decimal128: For high-precision decimals (important for financial values)
example :
{
"age": 30,
"price": 99.99,
"salary": NumberDecimal("1250.50")
}
3. Boolean
Accepts only two values: true or false.
example:
{
"isActive": true,
"hasDiscount": false
}
4. Date
Used to store dates and timestamps.
example:
{
"createdAt": ISODate("2023-05-24T10:30:00Z"),
"updatedAt": ISODate("2023-05-24T11:45:00Z")
}
5. Arrays
Allows storing multiple values of different types in a single field.
example:
{
"tags": ["technology", "databases", "NoSQL"],
"scores": [85, 92, 78]
}
6. Embedded Documents
One of MongoDB’s most powerful features, enabling documents to be nested within other documents.
example:
{
"user": {
"firstName": "Jane",
"lastName": "Smith",
"address": {
"city": "New York",
"country": "USA"
}
}
}
7. ObjectId
A unique identifier automatically generated for each document.
example:
{
"_id": ObjectId("507f1f77bcf86cd799439011")
}
8. Null
Represents a non-existent or unknown value.
example:
{
"middleName": null
}
9. Binary Data
For storing binary data like images or files.
example:
{ "image": BinData(0, "SGVsbG8gd29ybGQ=") }
10. Regular Expressions
Allows storing text search patterns.
example:
{ "pattern": /^MongoDB/i }