🍃 MongoDB Tutorial

MongoDB Data Types Explained (String, Int, Array, ObjectId & More)

A complete list of MongoDB's supported BSON data types — String, Integer, Boolean, Array, Date, ObjectId, Binary data, and more — with what each is used for.

MongoDB Data Types

Because MongoDB documents have a dynamic schema, every field can hold any of these BSON data types:

  1. String — the most common type for storing text. Strings must be UTF-8 valid.
  2. Integer — stores a numeric value, either 32-bit or 64-bit depending on your server.
  3. Boolean — stores true or false.
  4. Double — stores floating-point (decimal) values.
  5. Min / Max keys — compares a value against the lowest and highest possible BSON values.
  6. Arrays — stores a list of values (of any type) under a single key.
  7. Timestamp — handy for recording when a document was created or modified.
  8. Object — used for embedded (nested) documents.
  9. Null — stores an explicit null value.
  10. Date — stores a date/time in UNIX time format. You can construct your own with a specific day, month, and year.
  11. Object ID — the special type used for the _id field that uniquely identifies a document.
  12. Binary data — stores raw binary data.
  13. Code — stores JavaScript code directly inside a document.
  14. Regular expression — stores a regex pattern as a field value.

Example

A single document can freely mix these types:

db.emp.insertOne({
  name: "Roshan",              // String
  age: 24,                     // Integer
  isActive: true,               // Boolean
  rating: 4.5,                 // Double
  marks: [100, 200, 300],       // Array
  joinedAt: new Date(),         // Date
  address: { city: "Pune" }     // Object (embedded document)
})

Common Errors & Troubleshooting

  • Numbers coming back as strings (or vice versa) — since MongoDB has no fixed column types, inserting "25" and 25 into the same field across different documents both "work," but find({ age: 25 }) won't match a document where age was stored as the string "25". Be consistent about which type you insert.
  • Dates stored as plain strings instead of the Date type — new Date("2024-06-01") and the string "2024-06-01" look similar but behave very differently in queries — date range queries ($gte/$lte) only work correctly against a real Date, not a string that merely looks like one.
  • Assuming arrays need a fixed length or type — a single array field can freely mix types ([1, "two", true]) — there's no schema enforcing consistency unless you add one yourself (see the Constraints-equivalent: MongoDB's schema validation, an advanced topic beyond this course).

Key Takeaways

  • MongoDB has no fixed column types — every field's type is decided per-document.
  • Arrays and embedded objects are first-class types, not workarounds.
  • _id always uses the ObjectId type unless you explicitly override it.