0
0
MongodbDebug / FixBeginner · 3 min read

How to Fix Document Exceeds Maximum Size Error in MongoDB

The 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.

javascript
db.users.insertOne({
  name: "Alice",
  profilePicture: new BinData(0, "...very large base64 string..."),
  posts: Array(100000).fill({ text: "Sample post" })
})
Output
MongoError: document exceeds maximum size of 16777216 bytes
🔧

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.

javascript
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));
Output
Inserted 100000 posts as separate documents; user document size is small and valid
🛡️

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.

Key Takeaways

MongoDB documents cannot exceed 16MB in size.
Split large data into multiple documents or use GridFS for big files.
Avoid embedding huge arrays or files directly inside documents.
Validate document size before inserting or updating to prevent errors.
Design schemas with references to keep documents small and efficient.