Open In App

DataTypes in MongoDB

Last Updated : 26 Feb, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

MongoDB, a leading NoSQL database, uses BSON (Binary JSON) format to store documents, offering a wide range of data types that allow flexible and efficient data storage. Understanding the different data types in MongoDB is crucial for designing effective schemas, optimizing queries, and ensuring seamless application performance.

In this article, We will learn about the data types in MongoDB by understanding the various data types in detail with real-world examples.

MongoDB Data Types

In MongoDB, the documents are stored in BSON which is the binary encoded format of JSON and using BSON we can make remote procedure calls in MongoDB. BSON data format supports various data types. MongoDB supports a wide range of data types, from strings to arrays. Below are the most commonly used MongoDB data types, explained with practical examples.

1. String

This is the most commonly used data type in MongoDB to store data, BSON strings are of UTF-8. So, the drivers for each programming language convert from data types to the string format of the language to UTF-8 while serializing and de-serializing BSON. The string must be a valid UTF-8. 

Example: In the following example we are storing the name of the student in the student collection:

Here, the name field is a string representing the student’s name.

Key Features:

  • Stored in UTF-8 format.
  • Ideal for storing text-based data.

2. Integer

In MongoDB, the integer data type is used to store an integer value. We can store integer data type in two forms 32-bit signed integer and 64-bit signed integer. These are used to store whole numbers, such as ages, counts, or any other numerical data that doesn’t require decimal points.

Example: In the following example we are storing the age of the student in the student collection:

In this example, age is stored as an integer.

Key Features:

  • Can be represented as either a 32-bit or 64-bit signed integer.
  • Suitable for storing whole numbers.

3. Double

The double data type is used for storing floating-point numbers (decimal values). It’s commonly used for storing data that requires decimal precision, such as prices, percentages, or scores.

Example: In the following example we are storing the marks of the student in the student collection:

In this example, marks is stored as a double to store the decimal value.

Key Features:

  • Used to store floating-point numbers.
  • Ideal for data requiring decimal precision.

4. Boolean

The boolean data type stores one of two values: true or false. It’s used for representing binary states, such as “active/inactive” or “pass/fail.”

Example: In the following example we are storing the final result of the student as pass or fail in boolean values.

In this example, the passed field is a boolean value indicating whether the student passed or failed.

Key Features:

  • Stores true or false values.
  • Commonly used for binary states.

5. Null

The null data type stores a null value. This is useful when you want to represent the absence of data, such as an optional field that may not be set.

Example: In the following example,  the student does not have a mobile number so the number field contains the value null.

Here, phone_number is set to null, indicating that the student has not provided a phone number.

Key Features:

  • Represents the absence of data.
  • Used for missing or undefined values.

6. Array

The array data type allows us to store multiple values in a single field.MongoDB arrays can contain values of the same or different data types, providing flexibility in how you store collections of related data. In MongoDB, the array is created using square brackets([]). 

Example: In the following example, we are storing the technical skills of the student as an array.

In this example, the skills field stores an array of strings representing the student’s technical skills.

Key Features:

  • Stores multiple values in a single field.
  • Can hold values of different data types.

7. Object (Embedded Document)

Object data type stores embedded documents. Embedded documents are also known as nested documents. Embedded document or nested documents are those types of documents which contain a document inside another document. Embedded documents allow us to structure our data hierarchically, which is useful for representing more complex data models.

Example: In the following example, we are storing all the information about a book in an embedded document.

Here, the book field stores an embedded document with properties like title, author, and published.

Key Features:

  • Stores nested documents.
  • Useful for hierarchical data structures.

8. Object Id

Whenever we create a new document in the collection MongoDB automatically creates a unique object id for that document(if the document does not have it). There is an _id field in MongoDB for each document. The data which is stored in Id is of hexadecimal format and the length of the id is 12 bytes which consist:

  • 4-bytes for Timestamp value.
  • 5-bytes for Random values. i.e., 3-bytes for machine Id and 2-bytes for process Id.
  • 3- bytes for Counter

We can also create your own id field, but make sure that the value of that id field must be unique.

Example: In the following example, when we insert a new document it creates a new unique object id for it.

In this example, MongoDB automatically generates a unique _id for each document.

Key Features:

  • Unique identifier for each document.
  • Automatically generated by MongoDB.

9. Undefined

The undefined data type represents a value that is not defined. It is rarely used in modern MongoDB applications, as it has been replaced by the null value for most practical purposes.

Example: In the following example the type of the duration of the project is undefined.

In this example, the duration field is set to undefined.

Key Features:

  • Represents an undefined value.
  • Typically replaced by null.

10. Binary Data

The binary data data type stores binary information such as images, files, or encrypted data. Binary data is often used when working with non-textual data.

Example: In the following example the value stored in the binaryValue field is of binary type.

Here, the image field stores binary data.

Key Features:

  • Used for storing non-textual data (e.g., images, files).
  • Stored as binary data.

11. Date

Date data type stores date. It is a 64-bit integer which represents the number of milliseconds. BSON data type generally supports UTC datetime and it is signed. If the value of the date data type is negative then it represents the dates before 1970. There are various methods to return date, it can be returned either as a string or as a date object. Some method for the date:

  • Date(): It returns the current date in string format.
  • new Date(): Returns a date object. Uses the ISODate() wrapper. 
  • new ISODate(): It also returns a date object. Uses the ISODate() wrapper.

Example: In the following example we are using all the above method of the date:

In this example, the created_at field stores the current date and time.

Key Features:

  • Stores dates and times as 64-bit integers.
  • Commonly used for timestamps.

12. Min & Max key

The MinKey and MaxKey data types are used for internal comparisons. MinKey represents the lowest BSON element, while MaxKey represents the highest.

Example: 

Key Features:

  • Used for internal comparisons in queries.
  • Represents the lowest and highest BSON elements.

13. Symbol

This data type similar to the string data type. It is generally not supported by a mongo shell, but if the shell gets a symbol from the database, then it converts this type into a string type.

Example: 

14. Regular Expression

The regular expression data type is used to store regex patterns. MongoDB supports regex queries for performing pattern matching on string fields.

Example: In the following example we are storing the regular expression gfg:

In this example, the name field stores a regular expression to match names that contain “John” case-insensitively.

Key Features:

  • Used for pattern matching with regular expressions.
  • Useful for querying string data.

15. JavaScript

MongoDB allows us to store JavaScript code within documents using the JavaScript data type. This can be useful for storing code or expressions.

Example: In this example, we are using the JavaScript syntax in the shell:

Key Features:

  • Stores JavaScript code.
  • Useful for embedded code or expressions.

16. JavaScript with Scope

The JavaScript with Scope data type in MongoDB was used to store JavaScript code along with its scope (variables and functions). This feature has been deprecated in MongoDB 4.4 and is no longer recommended for use.

Example: In this example, we are using the JavaScript syntax in the shell:

Key Features:

  • Allowed storing JavaScript code with scope.
  • Deprecated in MongoDB 4.4.
  • Use alternatives like aggregation pipelines or external languages for dynamic code execution.

17. Timestamp

In MongoDB, this data type is used to store a timestamp. It is useful when we modify our data to keep a record and the value of this data type is 64-bit. The value of the timestamp data type is always unique.

Example: 

In this example, the updated_at field stores a timestamp value.

Key Features:

  • Used for time tracking.
  • Stores a 64-bit value

18. Decimal

This MongoDB data type store 128-bit decimal-based floating-point value. This data type was introduced in MongoDB version 3.4

Example: 

Decimal

Conclusion

MongoDB offers a rich set of data types that make it flexible and efficient for various application needs. From basic data types like strings and integers to advanced types like binary data, timestamps, and embedded documents, MongoDB allows developers to store and manage data in ways that traditional relational databases cannot. By understanding the different MongoDB data types and their use cases, we can design schemas that fit your application’s requirements and ensure efficient querying and data manipulation.

FAQs

What is the difference between ObjectId and String in MongoDB?

ObjectId is a specialized data type used as a unique identifier for documents, while String is a general-purpose data type for storing textual data.

How does MongoDB handle dates and times?

Dates are stored as 64-bit integers representing milliseconds since Unix epoch (January 1, 1970 UTC).

Can MongoDB store binary data like images or files?

Yes, MongoDB supports Binary Data type (BinData) for storing binary data such as images or files.

What is the significance of ObjectId in MongoDB documents?

ObjectId uniquely identifies each document in a collection, ensuring each document has a unique identifier even across distributed databases.



Next Article
Article Tags :

Similar Reads

three90RightbarBannerImg