MongoDB Data Types

Every piece of data stored in a MongoDB document has a type. A data type tells MongoDB what kind of value is being stored — a number, a piece of text, a date, a true/false value, and so on. Knowing the correct data type ensures data is stored accurately and queries return the right results.

MongoDB uses a format called BSON (Binary JSON) to store documents internally. BSON extends regular JSON by supporting additional data types that JSON does not have — like dates, integers, and binary data. However, when writing documents, the familiar JSON-style syntax is used.

Commonly Used MongoDB Data Types

1. String

A string holds text — letters, words, sentences, or any combination of characters. Strings are always wrapped in double quotes.

{
  "productName": "Wireless Keyboard",
  "brand": "Logitech"
}

Strings are the most common data type in MongoDB. Names, descriptions, categories, and statuses are usually stored as strings.

2. Integer

An integer stores whole numbers — numbers without decimal points. MongoDB supports two sizes of integers:

  • 32-bit integer — for smaller numbers (up to about 2.1 billion)
  • 64-bit integer — for very large whole numbers
{
  "studentAge": 20,
  "totalMarks": 450
}

3. Double

A double stores numbers with decimal points (floating-point numbers). It is the default number type in MongoDB when a decimal value is written.

{
  "productPrice": 1299.99,
  "rating": 4.5
}

4. Boolean

A boolean holds only two possible values: true or false. It is used for yes/no or on/off situations.

{
  "isActive": true,
  "isPremiumMember": false
}

5. Date

The Date type stores date and time information. MongoDB stores dates as the number of milliseconds since January 1, 1970 (UTC), but displays them in a readable format.

{
  "enrollmentDate": ISODate("2024-06-15T10:30:00Z"),
  "lastLogin": ISODate("2025-01-01T08:00:00Z")
}

ISODate() is a helper function in MongoDB that converts a date string into the proper Date type.

6. Array

An array stores a list of multiple values inside a single field. The values can be strings, numbers, objects, or even other arrays. Arrays are written inside square brackets [].

{
  "studentName": "Ankit Verma",
  "subjects": ["Mathematics", "Physics", "Chemistry"]
}

Arrays are very useful in MongoDB because a single field can hold multiple related values without needing a separate table or collection.

7. Object (Embedded Document)

An object, also called an embedded document, stores a nested set of key-value pairs inside a field. It is written inside curly braces {}.

{
  "employeeName": "Meena Joshi",
  "address": {
    "street": "12 MG Road",
    "city": "Bengaluru",
    "pincode": "560001"
  }
}

Instead of storing address in a separate collection, the entire address is embedded inside the employee document. This keeps related data together.

8. ObjectId

ObjectId is a special 12-byte type that MongoDB uses for the _id field by default. It is automatically generated when a document is inserted and is guaranteed to be unique across the collection.

{
  "_id": ObjectId("64f1a2b3c4d5e6f7a8b9c0d1"),
  "name": "Sunita Patel"
}

An ObjectId contains information about the time it was created, making it loosely sortable by creation time as well.

9. Null

The null type represents the intentional absence of a value. It is different from a missing field — a field set to null exists but has no value.

{
  "username": "rahul_dev",
  "middleName": null
}

10. Binary Data

The Binary (BinData) type stores raw binary data such as images, files, or encrypted content. This type is not used directly in queries but is useful when storing binary files inside documents.

{
  "fileName": "profile.jpg",
  "fileData": BinData(0, "c29tZWJpbmFyeWRhdGE=")
}

11. Timestamp

The Timestamp type is used internally by MongoDB for replication and logging purposes. It is different from the Date type. While Date is for general use in application data, Timestamp is mainly used by MongoDB's internal operations.

12. Regular Expression (Regex)

MongoDB supports storing and querying using regular expressions. This allows pattern-based searching inside string fields.

{
  "pattern": /^mongo/i
}

A regular expression like /^mongo/i finds all documents where the field value starts with the word "mongo" (case-insensitive).

Data Type Summary Table

Data TypeExample ValueCommon Use
String"Delhi"Names, descriptions, labels
Integer25Age, count, quantity
Double99.99Price, ratings, measurements
Booleantrue / falseFlags, status, on/off
DateISODate("2024-01-01")Timestamps, birth dates
Array["Math", "Science"]Multiple values in one field
Object{ "city": "Mumbai" }Nested data, address, metadata
ObjectIdObjectId("...")Unique document identifier
NullnullMissing or unknown value
BinaryBinData(...)Files, images, encrypted data

How Data Types Affect Queries

Data types directly affect how MongoDB handles comparisons and queries. For example, the number 25 (integer) and the string "25" are treated as completely different values. A query searching for age equal to 25 will not match a document where age is stored as "25".

// This finds documents where age is the number 25
db.students.find({ age: 25 })

// This finds documents where age is the string "25"
db.students.find({ age: "25" })

Storing the correct data type from the beginning avoids filtering errors and query mismatches later.

Checking Data Types in the Shell

The typeof keyword in JavaScript (which the MongoDB shell uses) helps check a value's type:

typeof "Hello"    // "string"
typeof 42         // "number"
typeof true       // "boolean"

For BSON-specific types like ObjectId or Date, the MongoDB shell provides helper methods to inspect and create them.

Summary

MongoDB supports a rich set of data types including strings, integers, doubles, booleans, dates, arrays, objects, ObjectIds, nulls, and binary data. Choosing the correct type for each field ensures data accuracy, proper comparisons in queries, and efficient storage. Arrays and embedded objects are particularly powerful in MongoDB, as they allow complex data structures within a single document without needing multiple collections.

Leave a Comment