How to optimize the MongoDB database
Optimize a simple example This part mainly explains how to optimize the performance of MongoDB. Let’s take a concrete example. Suppose our task is to display the front page of the blog – we want to display the last 10 posts. ts is the time field. The statement is as follows articles = db.posts.find().sort({ts:-1}); // get blog posts in reverse time order for (var i=0; i< 10; i++) { print(articles[i].getSummary());} Optimization #1: Create Index The first optimization is to create an index on ts for quick sorting. db.posts.ensureIndex({ts:1}); Using an index, the database can sort based on the index information, without looking at each document directly. It’s faster to do this. Optimization #2: Limit results MongoDB cursors return a set of documents, which we call chunks. This chunk may contain more than 10 objects. The extra objects are wasteful for our needs, A waste of network bandwidth and application server and database resources. We know the number of results we want, so we don’t need all of them. We can use the limit() method articles = db.posts.find().sort({ts:-1}).limit(10); // Up to 10 entries Now, we returned 10 entries from the client. Optimization #3: Query related fields Post objects are very large,…