PREVIOUS NEXT
Lecture Notes Of Day 4
MongoDB Data Types
Outcome:
Students will be able to identify and use different MongoDB data types in a
document.
1. Introduction to
MongoDB Data Types
MongoDB, being a
flexible, schema-less NoSQL database, allows you to store data in the form of documents
(which are JSON-like objects). Each document contains fields that store data,
and each field can have a different data type. MongoDB supports a wide
range of data types, which makes it easy to store different kinds of data such
as strings, numbers, booleans, and more.
Here are some commonly
used data types in MongoDB:
2. String
- Description:
A string in MongoDB is used to store text values. This data type is widely used for storing names, descriptions, and other textual data. - Example
Usage:
{
"name": "John Doe",
"address": "123 Elm
Street"
}
- Characteristics:
- Always
enclosed in double quotes (" ").
- Text
can contain alphabets, numbers, symbols, or spaces.
- MongoDB
stores strings in UTF-8 format.
3. Integer (Int32 and
Int64)
- Description:
Integers in MongoDB are used to store whole numbers. MongoDB supports two types of integers: Int32 (32-bit) and Int64 (64-bit). - Example
Usage (Int32):
{
"age": 25
}
- Example
Usage (Int64):
{
"population": NumberLong(1000000)
}
- Characteristics:
- Int32:
Used for small integers (values between -2,147,483,648 to 2,147,483,647).
- Int64:
Used for larger integers (greater than the range of Int32).
4. ObjectId
- Description:
ObjectId is a special type of identifier used by MongoDB to uniquely identify documents in a collection. Each document in MongoDB has a default _id field, which is of ObjectId type if not explicitly specified. - Example
Usage:
{
"_id": ObjectId("507f1f77bcf86cd799439011"),
"name": "Alice"
}
- Characteristics:
- An
ObjectId is a 12-byte identifier.
- The
first 4 bytes represent the timestamp when the document was created.
- The
next 5 bytes are a random value generated once per machine.
- The
next 3 bytes are the process ID.
- It
is unique across all documents, even across multiple servers.
5. Boolean
- Description:
The Boolean data type stores a true or false value. It is typically used for flags or binary values. - Example
Usage:
{
"isActive": true,
"isDeleted": false
}
- Characteristics:
- Used
for storing true or false values.
- Commonly
used for binary flags or conditions (e.g., whether a document is active
or deleted).
6. Date
- Description:
MongoDB uses the Date type to store date and time information. The date is stored as the number of milliseconds since the Unix epoch (January 1, 1970). - Example
Usage:
{
"createdAt": new Date("2023-01-01T10:00:00Z")
}
- Characteristics:
- Stores
both date and time.
- Date
values can be created using the new Date() constructor or by passing a
string representation of the date.
- MongoDB
uses ISODate format internally.
7. Array
- Description:
Arrays in MongoDB are used to store multiple values in a single field. Arrays can hold any data type, including strings, integers, sub-documents, and even other arrays. - Example
Usage:
{
"tags": ["mongodb", "database",
"NoSQL"]
}
- Characteristics:
- Arrays
can hold values of different types.
- You
can have arrays of strings, numbers, or even nested documents.
8. Embedded Documents
(Subdocuments)
- Description:
In MongoDB, you can store complex data structures as subdocuments within a document. These are useful for representing hierarchical data such as address details, orders, etc. - Example
Usage:
{
"name": "Bob",
"address": {
"street": "456 Maple
Avenue",
"city": "Metropolis",
"zip": "12345"
}
}
- Characteristics:
- A
subdocument is just a nested document.
- It
is useful for storing structured data within a document.
9. Null
- Description:
The null data type is used to represent an explicit absence of any value. - Example
Usage:
{
"middleName": null
}
- Characteristics:
- It
explicitly represents no value.
- Different
from an empty string, zero, or undefined.
10. Binary Data
- Description:
The BinData type in MongoDB is used to store binary data (e.g., images, files, or cryptographic data). - Example
Usage:
{
"profilePicture": BinData(0, "iVBORw0KGgoAAAANSUhEUgAA...")
}
- Characteristics:
- Stores
raw binary data.
- Can
be used to store files such as images or PDF documents.
11. Regular Expressions
- Description:
MongoDB allows you to store regular expressions as data. This is useful for performing pattern matching queries. - Example
Usage:
{
"emailPattern": /.*@gmail\.com$/
}
- Characteristics:
- Regular
expressions are used for pattern matching.
- Can
be used with $regex in queries for text searches.
12. MaxKey and MinKey
- Description:
MaxKey and MinKey are special types used in MongoDB to represent the maximum and minimum possible values. They are primarily used for comparisons in queries. - Example
Usage:
{
"maxValue": MaxKey(),
"minValue": MinKey()
}
- Characteristics:
- MaxKey
is the highest possible value in MongoDB.
- MinKey
is the lowest possible value.
13. Use Cases for MongoDB
Data Types
- String:
Storing names, addresses, descriptions, and any other textual data.
- Integer:
Storing age, count, or quantities that are numeric.
- ObjectId:
Automatically generated unique identifiers, commonly used for the _id
field.
- Date:
Used for storing timestamps, created/updated times, and other time-related
fields.
- Boolean:
Flag to represent true/false conditions, e.g., account active status.
- Array:
Storing lists of values like tags, categories, or multiple addresses.
- Embedded
Documents: Storing complex data such as user
profiles, address details, or product information.
- Binary
Data: Storing media files like images, PDFs, or audio
files.
- Regular
Expressions: Storing patterns for text matching
or validation.
14. Conclusion
MongoDB's data types
provide great flexibility and allow developers to work with a variety of data
formats. By understanding the different data types, you can structure your
documents effectively to store data in a way that aligns with your
application's needs. Properly choosing and using these data types will ensure
efficient storage, retrieval, and manipulation of your data.
15. Exercise
1.
Create a MongoDB document for a user's
profile, which includes:
o A
string for the name.
o An
integer for age.
o A
boolean for account status (active or inactive).
o An
array of strings for hobbies.
o A
date for account creation date.
o An
embedded document for the user's address with fields for street, city, and
postal code.
