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
}
}
}
}
])
Explore 500+ free tutorials across 20+ languages and frameworks.