How to Fix Document Exceeds Maximum Size Error in MongoDB
document exceeds maximum size error in MongoDB happens when a single document is larger than 16MB, the database limit. To fix it, split large data into smaller documents or use GridFS for storing large files instead of embedding them directly.Why This Happens
MongoDB limits each document to a maximum size of 16MB. If you try to insert or update a document that is larger than this limit, MongoDB throws an error. This usually happens when you embed large arrays or files directly inside a document.
db.users.insertOne({
name: "Alice",
profilePicture: new BinData(0, "...very large base64 string..."),
posts: Array(100000).fill({ text: "Sample post" })
})The Fix
To fix this, avoid storing huge data directly in one document. Instead, split large arrays into multiple documents or use MongoDB's GridFS to store large files. This keeps each document under the 16MB limit.
const user = { name: "Alice" }; // Store profile picture in GridFS instead of document // Store posts as separate documents in a posts collection // Example: Insert posts separately const posts = Array(100000).fill({ userId: user._id, text: "Sample post" }); posts.forEach(post => db.posts.insertOne(post));
Prevention
To avoid this error in the future, always monitor document size when designing schemas. Use references instead of embedding large arrays or files. Use GridFS for files larger than 16MB. Also, implement validation or linting in your code to check document size before inserting or updating.
Related Errors
Similar errors include:
- WriteConflict: Happens when multiple writes conflict on the same document.
- ExceededMemoryLimit: When aggregation pipeline uses too much memory.
- DocumentValidationFailure: When document does not meet schema validation rules.
Fixes usually involve schema design improvements and splitting data logically.