Data Types

Basic Data Types

String

// Basic string
{ name: "John Doe" }

// String with special characters
{ description: "Product with 50% discount!" }

// Empty string
{ title: "" }

// Multiline string
{ bio: "This is a\nmultiline\nstring" }

// String with quotes
{ message: "He said \"Hello World\"" }

// String with unicode
{ text: "Café résumé naïve" }

Number

// Integer
{ age: 25 }

// Double/Float
{ price: 99.99 }

// Negative number
{ temperature: -5.5 }

// Scientific notation
{ distance: 1.5e6 }  // 1,500,000

// Zero
{ count: 0 }

// Large numbers
{ population: 7800000000 }

Boolean

// True value
{ isActive: true }

// False value
{ isDeleted: false }

// Boolean in conditions
{ verified: true }

Null

// Null value
{ middleName: null }

// Missing field (different from null)
{ name: "John" }  // middleName field doesn't exist

// Explicit null assignment
{ status: null }

Date

// Current date
{ createdAt: new Date() }

// Specific date
{ birthDate: new Date("1990-05-15") }

// Date with time
{ orderDate: new Date("2023-12-25T10:30:00Z") }

// Date from timestamp
{ timestamp: new Date(1640995200000) }

// Date arithmetic
{ futureDate: new Date(Date.now() + 86400000) }  // Tomorrow

ObjectId

// Auto-generated ObjectId
{ _id: ObjectId() }

// Specific ObjectId
{ userId: ObjectId("507f1f77bcf86cd799439011") }

// ObjectId from string
{ productId: ObjectId("507f1f77bcf86cd799439011") }

// ObjectId in queries
{ _id: ObjectId("507f1f77bcf86cd799439011") }

Complex Data Types

Array

// Simple array
{ tags: ["javascript", "mongodb", "nodejs"] }

// Array of numbers
{ scores: [85, 92, 78, 96] }

// Array of objects
{ addresses: [
    { type: "home", street: "123 Main St", city: "New York" },
    { type: "work", street: "456 Business Ave", city: "Los Angeles" }
] }

// Mixed array
{ data: ["string", 42, true, { key: "value" }] }

// Empty array
{ items: [] }

// Nested arrays
{ matrix: [[1, 2, 3], [4, 5, 6], [7, 8, 9]] }

Object/Document

// Simple object
{ profile: { firstName: "John", lastName: "Doe" } }

// Nested object
{ user: {
    profile: {
        firstName: "John",
        lastName: "Doe",
        contact: {
            email: "john@example.com",
            phone: "+1-555-1234"
        }
    }
}}

// Object with arrays
{ product: {
    name: "Laptop",
    specs: {
        cpu: "Intel i7",
        ram: "16GB",
        storage: ["256GB SSD", "1TB HDD"]
    }
}}

// Empty object
{ metadata: {} }

Binary Data

// Binary data
{ image: BinData(0, "SGVsbG8gV29ybGQ=") }

// Binary with subtype
{ file: BinData(1, "base64encodeddata") }

// UUID as binary
{ uuid: BinData(3, "base64encodeduuid") }

Special Data Types

Regular Expression

// Regex pattern
{ pattern: /john/i }

// Regex with options
{ emailPattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/ }

// Regex object
{ regex: { $regex: "john", $options: "i" } }

JavaScript Code

// JavaScript function
{ function: function() { return "Hello World"; } }

// JavaScript with scope
{ code: Code("function() { return this.name; }", { name: "John" }) }

Timestamp

// Timestamp
{ timestamp: Timestamp(1640995200, 1) }

// Current timestamp
{ currentTime: Timestamp() }

Decimal128

// High precision decimal
{ price: NumberDecimal("99.99") }

// Financial calculations
{ amount: NumberDecimal("1234.5678") }

MinKey/MaxKey

// MinKey (smallest possible value)
{ minValue: MinKey }

// MaxKey (largest possible value)
{ maxValue: MaxKey }

Date and Time Types

ISODate

// ISO date string
{ isoDate: ISODate("2023-12-25T10:30:00Z") }

// ISO date with timezone
{ localDate: ISODate("2023-12-25T10:30:00-05:00") }

// ISO date from string
{ eventDate: ISODate("2023-12-25") }

Date Operations

// Date arithmetic
{ tomorrow: new Date(Date.now() + 24 * 60 * 60 * 1000) }

// Date comparison
{ isExpired: { $lt: ["$expiryDate", new Date()] } }

// Date formatting
{ formattedDate: { $dateToString: { format: "%Y-%m-%d", date: "$createdAt" } } }

Array and Object Operations

Array Elements

// Access array element
{ firstTag: "$tags.0" }

// Array length
{ tagCount: { $size: "$tags" } }

// Array slice
{ topScores: { $slice: ["$scores", 0, 3] } }

// Array element matching
{ highScores: { $filter: { input: "$scores", cond: { $gte: ["$$this", 80] } } } }

Object Fields

// Access nested field
{ firstName: "$profile.firstName" }

// Nested object access
{ email: "$profile.contact.email" }

// Object field existence
{ hasProfile: { $exists: "$profile" } }

Type Checking and Validation

Type Validation

// Check field type
{ isString: { $type: "string" } }

// Type checking in queries
{ age: { $type: "number" } }

// Multiple type checking
{ field: { $type: ["string", "number"] } }

Type Conversion

// String to number
{ numericAge: { $toInt: "$ageString" } }

// Number to string
{ ageString: { $toString: "$age" } }

// String to date
{ parsedDate: { $dateFromString: { dateString: "$dateString" } } }

// Date to string
{ dateString: { $dateToString: { date: "$date" } } }

Data Type Examples in Documents

User Document

{
    _id: ObjectId("507f1f77bcf86cd799439011"),
    username: "johndoe",
    email: "john@example.com",
    age: 30,
    isActive: true,
    profile: {
        firstName: "John",
        lastName: "Doe",
        birthDate: new Date("1993-05-15"),
        addresses: [
            {
                type: "home",
                street: "123 Main St",
                city: "New York",
                zipCode: "10001"
            }
        ]
    },
    tags: ["developer", "javascript", "mongodb"],
    scores: [85, 92, 78],
    metadata: {
        lastLogin: new Date(),
        loginCount: 42,
        preferences: {
            theme: "dark",
            notifications: true
        }
    }
}

Product Document

{
    _id: ObjectId("507f1f77bcf86cd799439012"),
    name: "Laptop",
    price: NumberDecimal("999.99"),
    category: "electronics",
    inStock: true,
    specs: {
        cpu: "Intel i7",
        ram: "16GB",
        storage: ["256GB SSD", "1TB HDD"],
        dimensions: {
            width: 15.6,
            height: 0.8,
            depth: 10.2
        }
    },
    tags: ["laptop", "computer", "electronics"],
    ratings: [4.5, 4.2, 4.8, 4.6],
    createdAt: new Date(),
    updatedAt: new Date()
}

Order Document

{
    _id: ObjectId("507f1f77bcf86cd799439013"),
    orderNumber: "ORD-2023-001",
    customerId: ObjectId("507f1f77bcf86cd799439011"),
    items: [
        {
            productId: ObjectId("507f1f77bcf86cd799439012"),
            name: "Laptop",
            price: NumberDecimal("999.99"),
            quantity: 1
        }
    ],
    total: NumberDecimal("999.99"),
    status: "pending",
    orderDate: new Date(),
    shippingAddress: {
        street: "123 Main St",
        city: "New York",
        state: "NY",
        zipCode: "10001",
        country: "USA"
    },
    payment: {
        method: "credit_card",
        cardLast4: "1234",
        amount: NumberDecimal("999.99")
    }
}

Type-Specific Queries

String Queries

// Case insensitive search
{ name: { $regex: /john/i } }

// String length
{ description: { $exists: true, $ne: "" } }

// String contains
{ tags: { $in: ["javascript"] } }

Number Queries

// Range queries
{ age: { $gte: 18, $lte: 65 } }

// Exact match
{ price: 99.99 }

// Multiple values
{ score: { $in: [85, 90, 95] } }

Date Queries

// Date range
{ createdAt: { $gte: new Date("2023-01-01"), $lt: new Date("2023-12-31") } }

// Recent documents
{ updatedAt: { $gte: new Date(Date.now() - 24 * 60 * 60 * 1000) } }

// Date comparison
{ expiryDate: { $lt: new Date() } }

Array Queries

// Array contains element
{ tags: "javascript" }

// Array contains all elements
{ tags: { $all: ["javascript", "mongodb"] } }

// Array size
{ tags: { $size: 3 } }

// Array element at position
{ "scores.0": { $gte: 80 } }

Object Queries

// Nested field query
{ "profile.firstName": "John" }

// Object field exists
{ "profile.contact": { $exists: true } }

// Nested object match
{ "profile.contact.email": "john@example.com" }

Data Type Best Practices

Performance Considerations

// Use appropriate types for indexing
{ userId: ObjectId("507f1f77bcf86cd799439011") }  // Better than string

// Use integers for counts
{ viewCount: 42 }  // Better than "42"

// Use dates for timestamps
{ createdAt: new Date() }  // Better than string timestamps

Validation

// Validate data types
{ age: { $type: "number", $gte: 0, $lte: 150 } }

// Validate email format
{ email: { $regex: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/ } }

// Validate required fields
{ name: { $exists: true, $ne: "" } }

Consistency

// Consistent naming
{ firstName: "John" }  // camelCase
{ last_name: "Doe" }   // snake_case (choose one style)

// Consistent data types
{ price: 99.99 }       // Always use NumberDecimal for money
{ quantity: 5 }        // Always use integer for counts

Last updated