Comments pushed into one MongoDB document until it hit the 16 MB limit
Our most popular product page stopped accepting comments with a BSONObjectTooLarge error. Long before that, every page view had been loading megabytes of comments nobody scrolled to. Why unbounded arrays fail twice, and how the bucket pattern and a separate collection fixed both problems.
Customers of our marketplace can comment on product pages. One afternoon, comments on the best-selling product (a phone case with tens of thousands of reviews and questions) started failing. The API returned 500, and the service log showed:
MongoServerError: BSONObjectTooLarge: Resulting document after update is larger than 16777216
at UpdateOneOperation.execute (.../mongodb/lib/operations/update.js:...)
code: 10334,
codeName: 'BSONObjectTooLarge'
16,777,216 bytes is 16 MiB, MongoDB's maximum BSON document size. The product document had reached it.
The schema stored comments inside the product:
{
_id: ObjectId("..."),
sku: "CASE-X12-BLK",
title: "...",
price: { amount: 1999, currency: "EUR" },
attributes: { ... },
comments: [
{ _id: ObjectId("..."), userId: "...", text: "...", createdAt: ISODate("..."), likes: 4 },
// ... 61,000 more
]
}
And new comments were added with $push:
await products.updateOne(
{ _id: productId },
{ $push: { comments: { _id: new ObjectId(), userId, text, createdAt: new Date(), likes: 0 } } }
);
It had been slow for a long time
The write failure was the visible symptom. When we checked the product page's performance history, the read side had been degrading for months. The slow query log (via the profiler) had entries like this:
db.setProfilingLevel(1, { slowms: 100 });
db.system.profile.find({ ns: "shop.products" }).sort({ ts: -1 }).limit(1);
{
op: 'query', ns: 'shop.products',
command: { find: 'products', filter: { sku: 'CASE-X12-BLK' } },
docsExamined: 1, nreturned: 1,
responseLength: 16634118,
millis: 412
}
One document examined, but a 16 MB response, every time someone opened that product page. The page showed ten comments, yet the service fetched the whole document, all 61,000 comments included, and threw most of it away. Our working set in memory was dominated by a handful of popular products, and each update rewrote a very large document.
Why the limit exists
MongoDB caps documents at 16 MiB so that a single document cannot use excessive memory or network bandwidth. GridFS exists for large binary data; for structured data, the limit is a signal that the model is wrong, not something to work around.
Unbounded arrays fail twice
Embedding related data is one of MongoDB's strengths. It is the right choice when the embedded data is bounded and read together with the parent: an order's line items, a user's few addresses. Comments on a product are neither:
- Unbounded: a popular product can collect any number of comments. There is no natural maximum.
- Not read together: the page shows 10, the product listing shows 0, and only a moderation tool wants them all.
Unbounded arrays cause two separate problems:
- The hard limit. Eventually the document cannot grow, and writes fail.
- The soft cost, long before that. Every read of the parent loads the array unless you project it
out. Every update to any field rewrites a large document in the storage engine's cache. Indexes on
array fields (a multikey index on
comments.createdAt, for example) have one entry per element, so a single document produces tens of thousands of index entries.
The MongoDB documentation calls this out as the "unbounded arrays" anti-pattern. We had followed a tutorial example that embedded comments in posts, without the caveat that it only works for small numbers.
Environment
| Item | Value |
|---|---|
| MongoDB | 7.0, replica set of 3 |
| Driver | Node.js driver 6.x |
| Collection | products, 380k documents |
| Largest documents | 6 products over 4 MB, 1 at the limit with 61k comments |
We considered two designs, and used a bit of both.
Option 1: a separate comments collection
The simplest correct model is one document per comment, referencing the product:
// comments collection
{ _id: ObjectId("..."), productId: ObjectId("..."), userId: "...", text: "...",
createdAt: ISODate("..."), likes: 0 }
db.comments.createIndex({ productId: 1, createdAt: -1 });
The product page fetches the product (now small) and the latest comments in one indexed query:
const recent = await comments
.find({ productId }, { projection: { text: 1, userId: 1, createdAt: 1, likes: 1 } })
.sort({ createdAt: -1 })
.limit(10)
.toArray();
Pagination uses the last createdAt and _id seen, not skip, so page 500 is as fast as page 1.
Option 2: the bucket pattern
For the "latest comments" view specifically, the bucket pattern can reduce the number of documents read. Comments are grouped into bucket documents with a fixed maximum size:
// comment_buckets collection
{
_id: ObjectId("..."),
productId: ObjectId("..."),
count: 50,
firstAt: ISODate("2026-10-01T..."),
lastAt: ISODate("2026-10-03T..."),
comments: [ /* at most 50 */ ]
}
Adding a comment appends to the current bucket, or creates a new one when it is full, in one atomic
update with upsert:
await buckets.updateOne(
{ productId, count: { $lt: 50 } },
{
$push: { comments: comment },
$inc: { count: 1 },
$min: { firstAt: comment.createdAt },
$max: { lastAt: comment.createdAt },
},
{ upsert: true }
);
If no bucket with room exists, the filter matches nothing and upsert creates a new bucket. The latest ten
comments come from reading the newest one or two buckets. Each document stays small (50 comments is roughly
20 to 40 KB), and growth is bounded by design.
Note the concurrency caveat: two concurrent inserts can both see no open bucket and both create one, leaving two partly filled buckets. That is harmless for comments; for data where it matters, an "open bucket" pointer on the parent or a unique index on a bucket sequence number avoids it.
What we chose
We used the separate collection as the source of truth, because comments are edited, liked, moderated and deleted individually, and one document per comment makes those operations simple. We did not need the bucket pattern's read savings: the indexed query for ten comments took about 2 ms. The bucket pattern is what we now use for the product view-event history, which is append-only and read in time ranges.
On the product document we kept a small, bounded summary that the listing page needs:
{ ..., commentStats: { count: 61204, lastAt: ISODate("...") } }
It is updated with $inc when a comment is added, and recomputed nightly from the comments collection.
Migration
We migrated product by product, with a script that streamed each large comments array into the new
collection with insertMany in batches of 1,000, then removed the array with $unset once the counts
matched. The API read from both locations during the migration (new collection first, then the array if
the product was not yet migrated).
1. Document sizes. After the migration, the largest product document is 38 KB:
db.products.aggregate([
{ $project: { size: { $bsonSize: "$$ROOT" } } },
{ $sort: { size: -1 } }, { $limit: 1 }
]);
// { _id: ..., size: 38912 }
We run this aggregation weekly and alert if any document in products exceeds 1 MB.
2. Page latency. The product page for the best-selling item went from 450 ms server time to 28 ms. The response from MongoDB dropped from 16 MB to under 50 KB per page view.
3. A schema guard. We added a JSON Schema validator on products that rejects a comments field, so
nobody can reintroduce the array by accident:
db.runCommand({
collMod: "products",
validator: { $jsonSchema: { not: { required: ["comments"] } } },
validationLevel: "strict"
});
4. Load test. We inserted 500,000 comments for one test product. Writes stayed at a steady 1 to 2 ms, and reading the latest ten stayed at about 2 ms throughout.
5. Security implications. The old design had a quiet abuse vector: any user able to post comments could grow a product document toward the limit and break comments for everyone on that product. Per-user rate limits existed, but the new model removes the shared limit entirely.
Takeaways
- Embed only data that is bounded and read with its parent. Comments, events and logs are not.
- Unbounded arrays slow every read and write long before they hit the 16 MB limit.
- Use a separate collection for items managed individually; use the bucket pattern for append-only data read in ranges.
- Watch document sizes with
$bsonSize, and guard the model with schema validation.
References: MongoDB document size limit, Avoid unbounded arrays, Group data with the bucket pattern, MongoDB schema validation.
Add a label
Embed this post
<iframe src="https://www.hibug.me/mongodb-document-16mb-unbounded-array" width="700" height="420" frameborder="0" loading="lazy"></iframe>
I work on performance and capacity for a marketplace with heavy read traffic and sharp daily peaks. My days are split between caches, Redis, document stores, connection pools and the load tests that tell us whether any of it will hold. Most of the problems I write about looked like scaling issues and turned out to be something smaller: a cache that refilled itself with stale data, a single command that froze Redis, a pool drained by one leaked connection, a load test that measured its own generator instead of the system. I try hard to measure before changing anything, so each post includes how we gathered numbers, what they showed and how we confirmed the fix under realistic load. I also include the optimisations that made things worse, because those taught me the most.
Comments
0No comments yet. Be the first to comment!
Sign In to post a comment.