MongoDB Best Practices

Chapter 2 · Practice 3 of 5

Never let an array grow without bound

From Schema design

Why it matters

A BSON document can be at most 16 MiB. An array that grows with every event, such as all log lines for a device, every follower of an account or every message in a chat, eventually hits that limit. Long before then, it slows down reads, updates and index maintenance on that array.

The MongoDB docs list unbounded arrays as the first schema anti-pattern. Fixes:

  • Move the items to their own collection with a reference back (deviceId), indexed.
  • Keep only a bounded subset embedded, for example with $push plus $slice to keep the latest 10.
  • Use the bucket pattern: one document per device per hour, each with a bounded array.

Ask of every array: what is the largest it can ever get?

Example

JavaScript
// Keep only the 10 most recent events on the device document
db.devices.updateOne(
  { _id: deviceId },
  { $push: { recentEvents: { $each: [event], $slice: -10 } } }
)