codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🍃

MongoDB

9 / 65 topics
6Data Modeling Concepts7Collections and Documents8Fields and Values9Data Types in MongoDB10Embedded References11Schema Design Principles
Tutorials/MongoDB/Data Types in MongoDB
🍃MongoDB

Data Types in MongoDB

Updated 2026-04-20
3 min read

Data Types in MongoDB

MongoDB is a NoSQL document database that stores data in flexible, JSON-like documents. Understanding the different data types available in MongoDB is crucial for effective schema design and efficient querying. This tutorial will cover all the fundamental data types supported by MongoDB, along with real-world examples and best practices.

Overview of Data Types

MongoDB supports a wide range of data types, which can be categorized into the following groups:

  1. Basic Types: These include strings, numbers, booleans, nulls, and undefined values.
  2. Array Type: Allows storing an ordered list of values.
  3. Document Type: MongoDB's core unit of data storage, similar to JSON objects.
  4. Binary Data Type: Used for storing binary files like images or PDFs.
  5. Date Type: Represents a specific point in time.
  6. ObjectID Type: A 12-byte unique identifier used as the default value for the _id field.
  7. Regular Expression Type: Allows pattern matching using regular expressions.
  8. JavaScript Code Types: Stores JavaScript code, which can be executed on the server.

Basic Data Types

Strings

Strings in MongoDB are UTF-8 encoded text. They are used to store textual data and can include any character from the Unicode character set.

// Example of a string in MongoDB
db.collection.insertOne({ name: "Alice" });

Numbers

MongoDB supports two types of numbers:

  1. 32-bit Integer: Stored as NumberInt.
  2. 64-bit Integer: Stored as NumberLong.

For floating-point numbers, MongoDB uses the standard JavaScript number type.

// Example of different number types in MongoDB
db.collection.insertOne({
  age: NumberInt(25),
  salary: NumberLong(100000),
  height: 5.9 // Floating-point number
});

Booleans

Booleans represent true or false values.

// Example of a boolean in MongoDB
db.collection.insertOne({ isActive: true });

Nulls and Undefined Values

MongoDB supports null values, which are used to indicate the absence of a value. The undefined type is not stored in documents but can be used in queries.

// Example of null in MongoDB
db.collection.insertOne({ status: null });

Array Type

Arrays allow storing an ordered list of values. Each element in an array can be of any data type, including other arrays or objects.

// Example of an array in MongoDB
db.collection.insertOne({
  tags: ["mongodb", "database", "noSQL"],
  scores: [85, 90, 78]
});

Document Type

Documents are the core unit of data storage in MongoDB. They are similar to JSON objects and can contain nested documents and arrays.

// Example of a document in MongoDB
db.collection.insertOne({
  name: "Bob",
  address: {
    street: "123 Main St",
    city: "Anytown"
  },
  hobbies: ["reading", "hiking"]
});

Binary Data Type

Binary data is used to store binary files such as images, PDFs, or any other type of file. MongoDB provides the BinData function to handle binary data.

// Example of binary data in MongoDB
const imageBuffer = fs.readFileSync("path/to/image.jpg");
db.collection.insertOne({ profilePicture: BinData(0, imageBuffer.toString("base64")) });

Date Type

MongoDB uses the JavaScript Date object to represent specific points in time. Dates are stored as 64-bit integers representing milliseconds since the Unix epoch.

// Example of a date in MongoDB
db.collection.insertOne({ createdAt: new Date() });

ObjectID Type

ObjectIDs are unique identifiers for documents. They are automatically generated by MongoDB when a document is inserted into a collection, unless explicitly specified.

// Example of an ObjectID in MongoDB
const ObjectId = require("mongodb").ObjectId;
db.collection.insertOne({ _id: new ObjectId(), name: "Charlie" });

Regular Expression Type

Regular expressions are used for pattern matching. They can be used in queries to search for documents that match a specific pattern.

// Example of a regular expression in MongoDB
db.collection.find({ name: { $regex: /^A/ } }); // Finds all names starting with 'A'

JavaScript Code Types

MongoDB supports storing and executing JavaScript code. This can be useful for server-side scripting or custom aggregation operations.

// Example of a JavaScript code in MongoDB
db.collection.insertOne({
  script: new Code("function() { return 'Hello, World!'; }")
});

Best Practices

  1. Use Appropriate Data Types: Choose the right data type for each field to optimize storage and performance.
  2. Avoid Using Undefined Values: Since undefined values are not stored, avoid using them in your documents unless necessary.
  3. Leverage ObjectIDs: Use ObjectIDs as primary keys for unique identification of documents.
  4. Efficient Queries with Indexes: Create indexes on fields that are frequently queried to improve performance.
  5. Regular Expression Optimization: Be mindful of regular expression usage, as they can be resource-intensive.

Conclusion

Understanding the data types available in MongoDB is essential for designing efficient and effective databases. By leveraging the right data types and best practices, you can optimize your MongoDB applications for better performance and scalability.


PreviousFields and ValuesNext Embedded References

Recommended Gear

Fields and ValuesEmbedded References