Wednesday, April 10, 2013

Optimizing MongoDB

PROBLEM:
How to optimize your MongoDB?

SOLUTION:
Here are some tips and tricks for optimizing your MongoDB deployment:

Design an efficient schema
1. When you’re designing your schema for MongoDB, think about the ways that you are going to access your data and the common access patterns. You want to take advantage of MongoDB’s flexible schema and design rich documents
2. A key question when designing a MongoDB schema is when to embed and when to link. Embedding is the nesting of objects and arrays inside a BSON document. Links are references between documents. Embedding is a bit like "prejoined" data. Operations within a document are easy for the server to handle. Links in contrast must be processed client-side by the application; the application does this by issuing a follow-up query.
Generally, for "contains" relationships between entities, embedding should be be chosen. Embedding documents when it should actually be linked would result in duplication of data.

Optimize your queries
Have slow database queries? Get more information on the performance of your queries using the explain feature. Using the mongo shell, invoke the explain() method on a cursor:

> db.collection.find(query).explain()

The result will be a document that contains the explain output:

{
   "cursor" : "BasicCursor",
   "indexBounds" : [ ],
   "nscanned" : 57594,
   "nscannedObjects" : 57594,
   "nYields" : 2 ,
   "n" : 3 ,
   "millis" : 108, 
   "indexOnly" : false,
   "isMultiKey" : false,
   "nChunkSkips" : 0 
}

Know your working set size
Retrieving data in RAM is orders of magnitude faster than disk. Think about the total database size in relation to the set of data that is active at any given point in time. If you want your queries to be fast, make sure that you have enough memory to hold your active working set in RAM.
Don’t forget your indexes. They take up memory too!

More Information

If you find this solution useful, you are welcome to press one of the ads in this page.. Thanks!