0
0
MongoDBquery~5 mins

Document size limits and structure rules in MongoDB

Choose your learning style9 modes available
Introduction

MongoDB stores data in documents. Knowing size limits and structure rules helps keep data safe and organized.

When designing a database schema to store user profiles.
When inserting large files or data into MongoDB.
When troubleshooting errors about document size limits.
When planning how to split data across multiple documents.
When validating data structure before saving to the database.
Syntax
MongoDB
No specific code syntax applies; these are rules about document size and structure.

Each MongoDB document can be up to 16 megabytes (MB) in size.

Documents are stored as BSON, which supports nested objects and arrays.

Examples
A simple document with fields and an array, well within size limits.
MongoDB
{ "name": "Alice", "age": 30, "hobbies": ["reading", "hiking"] }
Shows nested objects inside a document, which is allowed.
MongoDB
{ "_id": ObjectId("507f1f77bcf86cd799439011"), "profile": { "bio": "...", "social": { "twitter": "@alice" } } }
Documents must be smaller than 16MB; otherwise, MongoDB rejects them.
MongoDB
// Trying to insert a document larger than 16MB will cause an error.
Sample Program

This inserts a normal small document successfully. Trying to insert a document larger than 16MB will fail.

MongoDB
db.users.insertOne({ "name": "Bob", "age": 25, "bio": "A short bio." })

// Then try to insert a very large document (simulated here as a comment)
// db.users.insertOne({ "largeField": new Array(17000000).join('a') })
OutputSuccess
Important Notes

Always keep documents under 16MB to avoid errors.

Use embedded documents and arrays to organize data but avoid making documents too large.

For very large data, consider using GridFS or splitting data into multiple documents.

Summary

MongoDB documents have a maximum size of 16MB.

Documents can contain nested objects and arrays.

Keep documents small and well-structured for best performance.