MongoDB Data Types: Complete Guide With Examples
By upGrad
Updated on Sep 27, 2026 | 8 min read | 2.36K+ views
Share:
All courses
Certifications
More
By upGrad
Updated on Sep 27, 2026 | 8 min read | 2.36K+ views
Share:
Table of Contents
Key Highlights
Ready to build a stronger foundation in data science? Explore our data science courses and unlock higher-paying roles in data engineering and analytics.

Popular Data Science Programs
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.
String stores text and it has to be valid UTF-8, so it handles emojis, accents, and different languages.
A few things to know:
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 })
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 } })
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:
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
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.
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) })
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") })
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.
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
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.
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.
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:
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:
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()
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
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.
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:
db.users.find({ skills: "MongoDB" })
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.
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
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.
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:
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.
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.
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 aren't really data types you store in your documents. They're special values used for comparisons. Mostly behind the scenes.
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.
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
The right type affects storage size, query speed, and how well your data holds up over time. Here is a quick way to decide.
Also read: Understanding MongoDB Architecture: Key Components, Functionality, and Advantages
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.
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.
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.
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.
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.
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.
No, it's optional. MongoDB works fine without it, but validation is recommended for production systems to prevent type inconsistency as data grows.
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.
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.
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.
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.
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.
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
By submitting, I accept the T&C and
Privacy Policy
Start Your Career in Data Science Today
Top Resources