Tutorials Logic, IN info@tutorialslogic.com

MongoDB Data Types BSON Types

BSON Data Types

Choose MongoDB BSON types from value semantics, precision, sorting, indexing, and query behavior rather than storing every field as text.

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
        }
      }
    }
  }
])

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 }]
})
Before you move on

MongoDB Data Types BSON Types Mastery Check

3 checks
  • 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 Boundary

  • Same-looking values, different types

    A string date or numeric string does not sort and compare like a BSON date or number. Normalize types at the write boundary and query with matching BSON values.

MongoDB Questions Learners Ask

Queries and indexes treat strings, numbers, and dates as different types.

No. It is a 12-byte BSON identifier with a timestamp component.

Store BSON Date values in UTC and apply user timezones when displaying them.

Browse Free Tutorials

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