Explain the Document Model and BSON
The Document Model & BSON
At the foundation of MongoDB is the Document Data Model. Data is represented as semi-structured documents, serialized on disk and transmitted over the network in BSON (Binary JSON) format.
JSON vs BSON Comparison
| Attribute | JSON (JavaScript Object Notation) | BSON (Binary JSON) |
|---|---|---|
| Format | Human-readable text string | Binary encoded serialization |
| Supported Types | String, Number (IEEE 754), Boolean, Array, Object, Null | All JSON types + ObjectId, Date, Int32, Int64, Decimal128, Binary data, Timestamp, Regex |
| Traversal & Parsing Speed | Requires full string scanning and parsing | High-speed traversal with length prefixes and type markers |
| Space Overhead | Compact for text; no type metadata | Slightly larger due to field names, type headers, and length preambles |
| Maximum Document Size | Uncapped (limited by memory) | Enforced limit of 16 MB per document (use GridFS for larger files) |
Core BSON Data Types
ObjectId:12-byte globally unique identifier generated automatically for the_idfield.Date:64-bit integer representing milliseconds since the Unix epoch (UTC).Int32 & Int64:Explicit integer precision avoiding float inaccuracies.Decimal128:128-bit IEEE 754-2008 decimal floating point for high-precision monetary calculations.