MongoDB in MongoDB is best learned by connecting the rule to a product catalog or user activity store. Start with the smallest collection query, observe the output, and then add one realistic constraint so the concept becomes practical.
The key habit for this lesson is to watch document shape and index as it changes. That makes the topic easier to debug, easier to explain in interviews, and easier to use in real code without memorizing isolated syntax.
MongoDB Data Types needs more than a syntax memory trick. The important idea is to understand strings, numbers, booleans, arrays, embedded documents, ObjectId, dates, null, and type-aware queries in the exact situation where the page topic appears, then prove the behavior with a small working example and one edge case.
MongoDB stores data in BSON (Binary JSON) format, which extends JSON with additional data types. Understanding BSON types is essential for writing accurate queries and schemas. Each BSON type has a numeric type identifier used in $type queries.
| BSON Type | Type Number | Description |
|---|---|---|
| Double | 1 | 64-bit floating point number |
| String | 2 | UTF-8 encoded string |
| Object | 3 | Embedded document |
| Array | 4 | Ordered list of values |
| Binary | 5 | Binary data (files, images) |
| ObjectId | 7 | 12-byte unique identifier |
| Boolean | 8 | true or false |
| Date | 9 | 64-bit integer (milliseconds since epoch) |
| Null | 10 | Null value or missing field |
| Regular Expression | 11 | PCRE regex pattern |
| 32-bit Integer | 16 | Int32 - whole numbers up to ~2.1 billion |
| Timestamp | 17 | Internal MongoDB timestamp (replication) |
| 64-bit Integer | 18 | Int64 - large whole numbers |
| Decimal128 | 19 | High-precision decimal (financial data) |
db.examples.insertOne({
// String
name: "Alice Johnson",
// 32-bit Integer
age: NumberInt(29),
// 64-bit Integer
views: NumberLong(9876543210),
// Double (default for numbers)
score: 98.5,
// Decimal128 (for precise financial values)
balance: NumberDecimal("1234.56"),
// Boolean
active: true,
// Date
createdAt: new Date(), // current date/time
birthday: new Date("1995-03-15"), // specific date
isoDate: ISODate("2024-01-01T00:00:00.000Z"),
// ObjectId
userId: ObjectId("64a1f2c3e4b0a1b2c3d4e5f6"),
// Array
hobbies: ["reading", "cycling", "photography"],
// Embedded Object
address: { city: "New York", zip: "10001" },
// Null
deletedAt: null,
// Regular Expression
pattern: /^alice/i
})
// Date operations
let now = new Date()
let specificDate = new Date("2024-06-15T10:30:00Z")
// Find documents created after a specific date
db.users.find({ createdAt: { $gt: new Date("2024-01-01") } })
// ObjectId contains a timestamp - extract creation time
let id = ObjectId("64a1f2c3e4b0a1b2c3d4e5f6")
id.getTimestamp() // ISODate("2023-07-02T...")
// Generate a new ObjectId
let newId = new ObjectId()
print(newId.toString()) // "64b2e3f4a5c6d7e8f9a0b1c2"
// Query by type using $type operator
db.users.find({ age: { $type: "int" } }) // find Int32 fields
db.users.find({ name: { $type: "string" } }) // find string fields
db.users.find({ score: { $type: "double" } }) // find double fields
// Check type number
db.users.find({ balance: { $type: 19 } }) // Decimal128
// Convert types in aggregation pipeline
db.products.aggregate([
{
$project: {
name: 1,
// Convert string price to double
priceNum: { $toDouble: "$price" },
// Convert string date to Date
createdDate: { $toDate: "$createdAt" },
// Convert number to string
ageStr: { $toString: "$age" },
// Safe conversion with onError and onNull
safePrice: {
$convert: {
input: "$price",
to: "double",
onError: 0.0,
onNull: 0.0
}
}
}
}
])
Use MongoDB when the program needs a clear answer to a specific problem, not because the keyword looks familiar. In a real MongoDB task, first name the input, then name the transformation, then name the output. This small discipline shows whether the topic is being used correctly or only copied from an example.
A reliable practice flow is: create the smallest working collection query, add one normal case, add one edge case such as missing, repeated, empty, or boundary input, and then confirm the result with explain plan and sample documents. If the result surprises you, reduce the code until the behavior is visible again.
The most common trap here is copying the syntax before understanding the behavior. Avoid it by writing one sentence before the code that explains why MongoDB is the right choice. After the code runs, verify the lesson by doing this: change one input and explain the changed output.
MongoDB documents store BSON values, not just plain text. Common types include String, Boolean, Date, ObjectId, Array, embedded document, Int32, Int64, Decimal128, null, and binary data. Choosing the right type affects sorting, filtering, calculations, and how drivers convert values.
A number stored as a string may look fine in a document but sort incorrectly and break numeric comparisons. A date stored as text cannot be queried as a real date range as cleanly. Embedded documents and arrays are useful when related values are usually read together, but they should still match the query patterns of the application.
db.orders.insertOne({
_id: ObjectId(),
total: NumberDecimal('499.50'),
paid: true,
createdAt: new Date(),
items: [{ sku: 'BK-1', qty: 2 }]
})
Copying the syntax before understanding the behavior.
Write the expected behavior first, then make the example prove it.
Practicing only the perfect input.
Also test missing, repeated, empty, or boundary input before considering the lesson complete.
Looking only at the final output.
Trace document shape and index through each important step.
Storing every value as a string because it is easy to insert.
Store values in the type that matches how they will be compared, sorted, and calculated.
Use it when the problem matches the behavior shown in the example and when the result can be verified through explain plan and sample documents.
Start with a tiny case, then test missing, repeated, empty, or boundary input. The main warning sign is copying the syntax before understanding the behavior.
Trace document shape and index, predict the result, run the example, and compare your prediction with the actual output.
Queries, sorting, indexing, and calculations depend on types. The wrong type can produce incorrect results even when the document looks readable.
Explore 500+ free tutorials across 20+ languages and frameworks.