What are the implications of document size limits in MongoDB?
Instruction: Discuss the implications of MongoDB's document size limit and how to work within this constraint.
Updated
Official answer
MongoDB limits a BSON document to 16 MiB (16,777,216 bytes). This is the size of the encoded BSON document, including field names and encoding overhead, not just a file payload or the character count of a JSON representation. Compression does not turn an oversized logical document into a valid one.
Design for growth as well as the initial size. Embedding related data can simplify reads and single-document updates, but an unbounded array of events or comments can eventually exceed the limit. Use bounded embedding, separate referenced documents or an appropriate bucketing design when the data can grow without a useful bound. Each resulting document still has to fit, and splitting data changes query and atomicity requirements.
For example, keep an article's bounded metadata in one document and store an indefinitely growing comment history separately with an article identifier. Index and paginate that history according to the actual access pattern. This avoids growing a single article document indefinitely; it does not automatically make every query faster.
For file-like binary content larger than the limit, GridFS stores file metadata and chunks in separate documents. It is a file-storage API, not a larger-document mode for arbitrary nested application records. GridFS does not support multi-document transactions or an atomic replacement of an entire file's contents. If replacement needs a consistent published version, upload a new version and atomically change the application's reference after the upload succeeds, then handle cleanup of obsolete versions.
Measure encoded document sizes and expected growth before hitting the limit, and handle oversized inserts or updates explicitly. Choose embedding, references or GridFS based on access patterns, consistency requirements and operational needs. None removes the limit for an individual BSON document.