SyntaxStudy
Sign Up
MongoDB Beginner 1 min read

BSON Data Types

BSON extends JSON with additional data types that are important for database work. The most notable additions are ObjectId (a 12-byte unique identifier), Date (stored as a 64-bit Unix timestamp in milliseconds), Binary (for raw byte data), Decimal128 (for high-precision decimal arithmetic), and the Timestamp type used internally for replication. Understanding BSON types matters because the shell and drivers have specific ways to construct them, and type mismatches can cause queries to return no results. For example, querying a field stored as a string with an integer value will not match. MongoDB also supports the special MinKey and MaxKey sentinel values, which compare lower and higher than all other values respectively.
Example
// BSON type examples in mongosh

db.typesDemo.insertOne({
  // String
  name: "Alice",

  // 32-bit integer
  age: NumberInt(30),

  // 64-bit integer
  fileSize: NumberLong("9007199254740993"),

  // Double (default for JS numbers)
  price: 19.99,

  // High-precision decimal
  balance: NumberDecimal("12345.6789"),

  // Date
  createdAt: new Date(),

  // Boolean
  isActive: true,

  // Null
  deletedAt: null,

  // Array
  tags: ["nodejs", "mongodb"],

  // Embedded document
  address: { city: "London", country: "UK" },

  // Binary data
  avatar: BinData(0, "base64encodedstring=="),

  // ObjectId reference
  authorId: ObjectId("64a1f2b3c4d5e6f7a8b9c0d1")
})