Data Types in MongoDB
Introduction
Welcome to the first lesson of the "Schemas and Relations" course! This is the second course in our MongoDB learning path. In the first course, you mastered the fundamental CRUD operations. Now, we will focus on data modeling — the crucial step of structuring your data when building a project.
In this specific lesson, we'll explore the data types available in MongoDB. Understanding these data types will enable you to choose the right one for your needs, optimizing both performance and data integrity. We'll cover basic JSON data types and advanced BSON data types. Additionally, we'll discuss document limitations in terms of document size and nesting depth.
JSON Types
MongoDB stores data using the BSON format, which is an extension of JSON. Consequently, MongoDB supports all the data types available in JSON. Let’s explore these essential JSON types:
- String: Used to store textual data.
- Array: Can hold multiple values, which can be of various data types.
- Object: Represents a document within a document.
- Boolean: Holds
trueorfalsevalues. - Null: Represents the absence of a value.
- Floating-point number: The default type for all numbers in MongoDB, with or without decimal points.
JSON Types in Action
Here is a code snippet demonstrating the insertion of a document containing various JSON data types:
As mentioned earlier, BSON format extends JSON format and includes a few additional data types: ObjectId, Date, Timestamp, NumberLong, NumberDecimal, among others. For an in-depth look at BSON data types, refer to the BSON Specification and MongoDB's BSON Data Types.
ObjectId
