Tutorials Logic, IN info@tutorialslogic.com

MongoDB Data Types BSON Types

MongoDB Data Types BSON Types

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.

BSON Data Types

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)

Common BSON Types in a Document

Common BSON Types in a Document
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
})

Working with Dates and ObjectIds

Date and ObjectId Operations

Date and ObjectId Operations
// 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

Type Conversion and Checking

Type Conversion with $convert and $toInt

Type Conversion with $convert and $toInt
// 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
        }
      }
    }
  }
])

Applied guide for MongoDB

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.

  • Identify the exact problem solved by MongoDB.
  • Trace document shape and index before and after the main operation.
  • Keep one intentionally broken version and explain the fix.
  • Connect the example to a product catalog or user activity store so the idea feels concrete.

Choosing MongoDB data types that match real values

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.

  • Use Date for timestamps, not formatted date strings.
  • Use Decimal128 for money-like precision when needed.
  • Use ObjectId for MongoDB document identifiers.
  • Keep arrays for values that naturally belong to the parent document.

Order document with several BSON types

Order document with several BSON types
db.orders.insertOne({
  _id: ObjectId(),
  total: NumberDecimal('499.50'),
  paid: true,
  createdAt: new Date(),
  items: [{ sku: 'BK-1', qty: 2 }]
})
Key Takeaways
  • I can point to the exact document shape and index affected by this topic.
  • I verified the result with explain plan and sample documents instead of assuming it worked.
  • I can describe the main mistake: copying the syntax before understanding the behavior.
  • I can identify string, number, boolean, date, ObjectId, array, and embedded document values in a MongoDB document.
Common Mistakes to Avoid
WRONG Copying the syntax before understanding the behavior.
RIGHT Write the expected behavior first, then make the example prove it.
A one-line expectation turns the code from copied syntax into a testable idea.
WRONG Practicing only the perfect input.
RIGHT Also test missing, repeated, empty, or boundary input before considering the lesson complete.
The edge case is where most interview follow-up questions begin.
WRONG Looking only at the final output.
RIGHT Trace document shape and index through each important step.
Tracing makes debugging faster because you can see the first incorrect state.
WRONG Storing every value as a string because it is easy to insert.
RIGHT Store values in the type that matches how they will be compared, sorted, and calculated.
Explain the cause in one sentence before changing the code.

Practice Tasks

  • Build one small collection query that demonstrates MongoDB in a product catalog or user activity store.
  • Change the example to include missing, repeated, empty, or boundary input and record the difference.
  • Break the example by deliberately copying the syntax before understanding the behavior, then write the corrected version.
  • Explain the finished example in five bullet points: input, operation, output, failure case, and verification.
  • Create a customer document with ObjectId, name, birthDate, active status, addresses array, and loyalty points.

Frequently Asked Questions

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.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.