MongoDB Data Types: Complete Guide With Examples

By upGrad

Updated on Sep 27, 2026 | 8 min read | 2.36K+ views

Share:

Key Highlights

  • The MongoDB data core types include String, Boolean, Null, and ObjectId, the ones you will use in almost every collection.
  • Numeric data has four types, Int32, Int64, Double, and Decimal128, each suited to a different range or precision need.
  • Decimal128 is the only numeric type that avoids rounding errors, making it the right choice for money and financial data.
  • Date stores app-facing timestamps, while Timestamp is reserved for MongoDB's internal replication and sharding logs.
  • MinKey and MaxKey are not used in regular data, they exist to represent absolute lowest and highest values, mainly for sharding.
  • In this article, you will learn about all the MongoDB data types, how each one works, when to use it, and how to pick the right type for your data. 

Ready to build a stronger foundation in data science? Explore our data science courses and unlock higher-paying roles in data engineering and analytics.

MongoDB data types overview showing core, numeric, date and time, structural, advanced, and special data types.

Core MongoDB Data Types

These are the data types that you will run into in almost every MongoDB collection. Text, true/false values, empty values, and the ID. Learn these four first and everything else is built on them.

1. String

String stores text and it has to be valid UTF-8, so it handles emojis, accents, and different languages.

A few things to know:

  • There is no separate type for short text vs long text. Every string is just a string.
  • Strings are case sensitive. "Delhi" and "delhi" count as different values.
  • Need to search text properly, like full sentences? Use a text index.
  • MongoDB documents cannot go past 16MB. So if you are storing huge blocks of text, like full articles or logs, it is better to use GridFS or keep that text somewhere else.

2. Boolean

Boolean stores true or false. Use it for flags and switches, like whether a user is active or an order has shipped.

One common mistake: storing "true" as text instead of an actual boolean. That breaks your queries. Always use real true/false, not quotes.

db.users.find({ isActive: true })

3. Null

Null means a field exists, but has no value. It is different from a field that is just missing.

db.users.insertOne({ name: "Vikram Singh", middleName: null })

The tricky part here is a query like { middleName: null } matches both cases. Fields set to null and fields that do not exist at all. If you need to tell them apart, add $exists:

db.users.find({ middleName: { $exists: true, $eq: null } })

4. ObjectId

MongoDB gives every document a unique _id. If you don't provide one, MongoDB generates an ObjectId for you. It's 12 bytes. Small, but built to stay unique across different servers.

It's made of:

  • A timestamp (4 bytes)
  • A value tied to the machine and process (5 bytes)
  • An incrementing counter (3 bytes)

The timestamp lives right inside the ObjectId. So you can get the creation time without a separate date field.

db.orders.find().forEach(doc => print(doc._id.getTimestamp()))

This also means ObjectIds sort by insert order. Newer ones are always bigger than older ones.

Also read: Mongodb Tutorial: All you Need to know

Numeric Data Types in MongoDB

MongoDB doesn't treat all numbers the same. It has four numeric types. Each one differs in size and purpose. Picking the right one matters, especially for math or money.

5. Int32

Int32 stores whole numbers. No decimals. It uses 32 bits. That gives a range of about -2.1 billion to 2.1 billion.

Use it for small whole numbers. Stock count, age, ratings. Values that will never get huge.

db.products.insertOne({ name: "Notebook", stock: NumberInt(150) })

6. Int64

Int64 is like Int32, just bigger. It uses 64 bits, so it holds much larger whole numbers.

Use it when a number might outgrow Int32. Large order IDs, big counters, or timestamps in milliseconds.

db.transactions.insertOne({ orderId: NumberLong("9223372036854775807") })

7. Double

Double stores decimal numbers. It's MongoDB's default type when you insert a number with a decimal point.

db.products.insertOne({ name: "Notebook", price: 249.99 })

Doubles work fine for everyday decimals. But they're not perfectly exact. Floating point math can cause small rounding errors. Fine for most cases. Not fine for money.

8. Decimal128

Decimal128 stores decimals with exact precision. No rounding errors.

Use it for money, invoices, or any calculation that must be exact.

db.invoices.insertOne({ amount: NumberDecimal("1499.95") })

Also read: MongoDB Tutorial for Beginners: Learn MongoDB in Simple Steps

Int32 vs Int64 vs Double vs Decimal128

Here is a simple way to think about it:

Type

Stores

Use it for

Int32 Whole numbers (small range) Counters, quantities, ratings
Int64 Whole numbers (large range) Big IDs, large counters, ms timestamps
Double Decimals (approximate) General decimal values, measurements
Decimal128 Decimals (exact) Money, billing, financial data

Here is an important rule, if it is money, use Decimal128. If it is a big whole number, use Int64. Everything else, Int32 or Double works fine.

Looking to make the shift into AI and data-driven roles? Explore our M.Sc. in Artificial Intelligence and Data Science and build the expertise needed to lead in this fast-growing field.

Free Courses

Explore courses related to Data Science
Case Study using Tableau, Python and SQL
Case Study using Tableau, Python and SQL
10.58K+ learners
10 hrs of learning
Introduction to Tableau
Introduction to Tableau
8.5K+ learners
8 hrs of learning
Data Science in E-commerce: Pricing & Marketing Analytics

MongoDB Date and Time Data Types

MongoDB has two types that deal with time. They sound similar, but they are used for very different things. One is for your actual application data. The other is mostly internal.

9. Date

Date stores a specific point in time. It is just a number, the milliseconds since January 1, 1970 (called the Unix epoch).

db.orders.insertOne({ product: "Keyboard", orderedAt: new Date() })

You can also set a specific date instead of using the current time:

db.orders.insertOne({ product: "Mouse", orderedAt: new Date("2026-01-15") })

A few things to remember:

  • Date does not store a time zone. It stores a plain timestamp. Your app or driver handles the time zone conversion when displaying it.
  • Store dates as an actual Date type like "2026-01-15".
  • Use Date for anything the user is facing: order dates, sign-up dates, appointment times, and so on.

10. Timestamp

Timestamp looks like Date, but it is not meant for your application data. MongoDB uses it internally, mainly in the oplog, to track replication and sharding events.

A Timestamp is made of two parts:

  • A 32-bit value for the time (seconds since epoch)
  • A 32-bit counter, to keep operations in order within the same second

You'll rarely create one yourself. It mostly shows up if you're inspecting MongoDB's internals or working with replication.

db.system.replset.find()

Date vs Timestamp

Simple way to remember the difference:

Type

Used for

Precision

Who uses it

Date Your application data Milliseconds You, in your app
Timestamp MongoDB's internal operations Seconds + counter MongoDB itself (oplog)

Rule, if you are storing a date or time for your app, always use Date. Never use Timestamp for that. Timestamp is reserved for MongoDB's own replication logic, not for things like "created at" or "last login" fields.

Also read: What Is MongoDB? Introduction, Data Modeling, Terminology & Hierarchy

Data Science Courses to upskill

Explore Data Science Courses for Career Progression

background

Liverpool John Moores University

MS in Data Science

Double Credentials

Master's Degree18 Months

Placement Assistance

Certification6 Months

Structural MongoDB Data Types

MongoDB isn't limited to storing flat, simple values. It can also store lists and nested documents inside a single document. This is one of the biggest reasons people choose MongoDB over a traditional table-based database.

11. Array

Array stores a list of values inside one field. The values can be the same type, or mixed types.

db.users.insertOne({ name: "Priya Mehta", skills: ["JavaScript", "MongoDB", "Node.js"] })

You can even mix data types in the same array:

db.orders.insertOne({ product: "Laptop", tags: ["electronics", 2026, true] })

A few practical points:

  • You can query arrays directly. MongoDB checks if any element matches:
db.users.find({ skills: "MongoDB" })
  • Arrays can hold other arrays or objects too. That's how you build things like a list of addresses or a list of order items inside one document.
  • If an array keeps growing without limit, like logging every single event forever, it can bloat your document size. Keep that in mind before designing a schema around large arrays.

12. Object or Embedded Document

Object lets you nest a full document inside another document. Instead of linking to a separate collection, you keep related data together in one place.

db.users.insertOne({
  name: "Karan Malhotra",
  address: {
    city: "Delhi",
    pincode: "110001",
    country: "India"
  }
})

To query a nested field, use dot notation:

db.users.find({ "address.city": "Delhi" })

Embedded documents work well when the nested data is always accessed together with the parent, like a user and their address. It saves you from doing a separate lookup or join.

But if the nested data grows large or needs to be queried on its own often, like thousands of order line items, it's usually better to use a separate collection instead of embedding everything.

Array vs Object

Quick way to tell them apart:

Type

Structure

Best for

Array Ordered list of values Multiple values under one field, like tags, skills, or items
Object Key-value nested document Grouping related fields together, like an address or profile

Also read: The Future Scope of MongoDB: Advantages, Improvements & Challenges

Advanced MongoDB Data Types

These types do not show up as often. But they are useful for specific jobs, storing files, matching patterns, or saving actual code inside a document.

13. Binary Data

Binary Data stores raw, non-text data. Think images, PDFs, encrypted values, or UUIDs.

db.files.insertOne({
  name: "profile-photo.png",
  data: BinData(0, "SGVsbG8gV29ybGQ=")
})

A few things worth knowing:

  • Binary data is stored as-is. MongoDB does not try to interpret or parse it.
  • Small files can be stored directly as Binary Data. Larger files, anything close to or over 16MB, should use GridFS instead, since that's built to handle big files in chunks.
  • Binary Data is also commonly used for storing UUIDs, when you need a unique ID format different from ObjectId.

14. Regular Expression

Regular Expression stores a pattern, the same kind you'd use in JavaScript regex. It lets you match text patterns directly in your queries.

db.users.find({ name: { $regex: "^Sh", $options: "i" } })

You can also store a compiled regex pattern as a field value, though this is far less common than using regex inside a query.

15. JavaScript

JavaScript stores actual JavaScript code as a value in a document. It was originally meant to be used with server-side functions like $where or map-reduce.

db.users.insertOne({
  name: "Sample Script",
  validate: function() { return this.age > 18; }
})

In practice, this type is rarely used today. Most modern MongoDB apps handle logic in the application layer, not inside the database. It still exists for backward compatibility.

16. JavaScript with Scope

JavaScript with Scope is the same idea, but it also stores a set of variables (a "scope") alongside the code, so the function has access to specific values when it runs.

{
  code: "function() { return this.price > minPrice; }",
  scope: { minPrice: 100 }
}

Also read: Most Common MongoDB Commands for MongoDB Beginners

MinKey and MaxKey Data Types

MinKey and MaxKey aren't really data types you store in your documents. They're special values used for comparisons. Mostly behind the scenes.

17. MinKey

MinKey is always the smallest possible value in BSON. No matter what you compare it to, MinKey is considered lower.

db.data.find({ field: { $gt: MinKey() } })

MongoDB uses MinKey internally, especially in sharding, to represent the lowest boundary of a shard's range.

18. MaxKey

MaxKey is the opposite. It's always the largest possible value in BSON. Everything else is considered smaller than it.

db.data.find({ field: { $lt: MaxKey() } })

Like MinKey, MaxKey shows up mostly in sharding, marking the upper boundary of a shard's range.

Also read: Top 20 MongoDB Project Ideas for Beginners with Source Code in 2026

How to Choose the Right MongoDB Data Type

The right type affects storage size, query speed, and how well your data holds up over time. Here is a quick way to decide.

Match the Type to the Value

  • Text → String
  • True/false → Boolean
  • Small whole number → Int32
  • Large whole number → Int64
  • Decimal, rounding OK → Double
  • Money or exact decimals → Decimal128

Decide: Embed or Separate?

  • Always used with its parent (like an address) → Object
  • A list of similar items (like tags) → Array
  • Large, frequently queried on its own, or shared across documents → separate collection instead

Common Mistakes to Avoid

  • Dates as strings (breaks sorting and date math)
  • Numbers as strings without good reason
  • Double for money (use Decimal128)
  • Timestamp for app fields like "created at" (that's for MongoDB's internal use)

Quick Check

  1. Will I do math on this? → Keep it numeric.
  2. Does precision matter? → Decimal128, not Double.
  3. Will this grow unbounded? → Rethink the array.
  4. Queried often on its own? → Maybe its own collection.

Also read: Understanding MongoDB Architecture: Key Components, Functionality, and Advantages

Conclusion

MongoDB offers far more than strings and numbers. Types like Decimal128, Array, and Object each solve a specific problem, whether it's storing money accurately, nesting related data, or supporting internal replication.

The key rule: pick a type based on what the data actually is, not what it looks like. A phone number isn't a number. A date shouldn't be a string. Money should never be a Double. Getting this right early saves you from messy migrations and broken queries later.

Once you're comfortable with these types, the natural next step is learning indexing strategies and schema design patterns, since how you structure data matters as much as which types you pick.

Have questions about which course fits your career goals? Book a free consultation call with our experts today. 

Frequently Asked Questions (FAQs)

1. Can a single field have different data types across documents in the same collection?

Yes. MongoDB doesn't enforce a fixed type per field unless you add schema validation. It's technically allowed, but it's best avoided since it makes queries and aggregations unpredictable.

2. Does changing a field's data type require a migration?

Yes, if you want existing documents to match the new type. MongoDB won't auto-convert old values, so you'd typically need to update the field across all documents.

3. Why does my number field sometimes show up as a Double even though I inserted a whole number?

Many drivers and shell environments default to Double when a number is inserted without specifying an exact type. This is a common surprise for people new to MongoDB.

4. Is there a performance difference between data types when querying?

Yes, to some extent. Simple types like Int32, Boolean, and ObjectId compare faster than Decimal128 or large strings. Staying consistent with a field's type across documents matters more for performance than the type itself.

5. What happens if I query a field using the wrong data type?

MongoDB won't throw an error, it will just return no matches. A String "100" and a Number 100 are treated as different values entirely.

6. Is schema validation mandatory in MongoDB?

No, it's optional. MongoDB works fine without it, but validation is recommended for production systems to prevent type inconsistency as data grows.

7. Which MongoDB data type takes up the most storage space?

It depends on the value, but Binary Data and large embedded Objects or Arrays tend to use the most space. Simple types like Boolean and Int32 are the smallest.

8. Can two different data types be considered equal in a MongoDB query?

No. MongoDB comparisons are type sensitive. A value stored as a Number will never match a query looking for the same value as a String.

9. Does MongoDB automatically pick a data type if I don't specify one?

Yes. MongoDB infers the type based on how the value is written. A number with a decimal defaults to Double, plain text becomes a String, and so on, unless you explicitly tell it otherwise.

10. Are ObjectId and UUID the same thing?

No. ObjectId is MongoDB's own 12-byte identifier format, generated automatically. UUID is a separate, more universal identifier format, usually stored as Binary Data when used in MongoDB.

11. Why do some fields return unexpected results when sorted?

This usually happens when a field holds mixed data types across documents, like some values stored as Strings and others as Numbers. MongoDB sorts by BSON type order first, then by value, which can produce unexpected ordering.

upGrad

993 articles published

We are an online education platform providing industry-relevant programs for professionals, designed and delivered in collaboration with world-class faculty and businesses. Merging the latest technolo...

Speak with Data Science Expert

+91

By submitting, I accept the T&C and
Privacy Policy

Start Your Career in Data Science Today

Top Resources

Recommended Programs

IIIT Bangalore logo

IIIT Bangalore

Executive Diploma in DS & AI

360° Career Support

Executive Diploma

12 Months

Liverpool John Moores University Logo
bestseller

Liverpool John Moores University

MS in Data Science

Double Credentials

Master's Degree

18 Months

upGrad

Bootcamp

6 Months