MongoDB Best Practices
Store all data for a record in a single document: This is about leveraging MongoDB's document-oriented nature. Keeping related data together reduces the need for joins and improves read performance.
Avoid large documents: MongoDB has a document size limit (16MB). Large documents can slow down operations. It's also about working efficiently with the data in memory and keeping the working set size manageable.
Avoid unnecessarily long field names: Since field names are stored with each document, shorter names help reduce storage space. However, don't sacrifice clarity.
Eliminate unnecessary indexes: Indexes speed up reads but slow down writes and consume disk space. Keeping only necessary indexes optimizes performance and storage.
Remove indexes that are prefixes of other indexes: If you have an index on
{a: 1}
and another on{a: 1, b: 1}
, the first one is often unnecessary. MongoDB can use the compound index for queries using the single field index.
Camel Case:
Camel case merges words, with each word starting with a capital letter except for the first word. It's commonly used in programming languages like JavaScript.
Example:
userName
,userEmail
,accountBalance
,numberOfOrders
Snake Case:
Snake case separates words with underscores and doesn't capitalize letters. It's frequently used in languages like Python, especially where readability is emphasized.
Example:
user_name
,user_email
,account_balance
,number_of_orders
MongoDB community and documentation often favor camelCase for field names, reflecting its JSON-like document structure and JavaScript roots. This is more about consistency with JavaScript and JSON object property naming conventions rather than a special feature or enforced standard by MongoDB.
Last updated