Tutorials Logic, IN info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Website Development
Practice
Quiz Challenge Interview Questions Certification Practice
Tools
Online Compiler JSON Formatter Regex Tester CSS Unit Converter Color Picker
Compiler Tools

MongoDB Data Types — BSON Types Guide

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 TypeType NumberDescription
Double164-bit floating point number
String2UTF-8 encoded string
Object3Embedded document
Array4Ordered list of values
Binary5Binary data (files, images)
ObjectId712-byte unique identifier
Boolean8true or false
Date964-bit integer (milliseconds since epoch)
Null10Null value or missing field
Regular Expression11PCRE regex pattern
32-bit Integer16Int32 - whole numbers up to ~2.1 billion
Timestamp17Internal MongoDB timestamp (replication)
64-bit Integer18Int64 - large whole numbers
Decimal12819High-precision decimal (financial data)
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 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
// 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
        }
      }
    }
  }
])

Ready to Level Up Your Skills?

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