Introduction
Knowing what not to do helps keep your database fast and easy to use. Avoiding bad habits stops problems before they start.
Knowing what not to do helps keep your database fast and easy to use. Avoiding bad habits stops problems before they start.
No specific syntax; these are common mistakes to avoid in MongoDB usage.// Example of storing large arrays inside documents { _id: 1, name: "User", activities: ["login", "logout", "purchase" /* ... thousands more ... */] }
// Example of deeply nested documents { _id: 2, user: { profile: { address: { street: "123 Main St", city: "Townsville", zip: "12345" } } } }
// Example of using unindexed queries // Query without index on 'email' db.users.find({ email: "user@example.com" })
// Example of frequent updates on large documents // Updating a big document many times per second
Separating comments into their own collection avoids huge documents and makes queries faster.
// Example showing a bad pattern and a better way // Bad: Storing many comments inside one post document { _id: 1, title: "Post", comments: [ { user: "Alice", text: "Nice!" }, { user: "Bob", text: "Great!" }, // ... hundreds more ... ] } // Better: Store comments in a separate collection // posts collection { _id: 1, title: "Post" } // comments collection { postId: 1, user: "Alice", text: "Nice!" } { postId: 1, user: "Bob", text: "Great!" }
Always index fields you query often to speed up searches.
Avoid very large documents; split data into smaller pieces.
Keep document structure simple to make queries easier.
Avoid storing huge arrays inside one document.
Do not nest documents too deeply.
Use indexes to speed up queries.
Split frequently updated or large data into separate documents or collections.
{ name: "Alice", address: { city: "NY", zip: 10001 } } has shallow nesting: address contains city and zip directly.{ name: "Dave", address: "New York" } uses a string for address, which is valid but less structured.Pass the test and this pattern moves unknown