I am a "famous" Hacker in China. You can't even like my posts (Goutou.wep).Copy the code

Optimization plan 1: Create an index

Creating an index on a field of a query condition, or on a field of a sort condition, can significantly improve performance:

db.posts.ensureIndex({ts:1});
Copy the code

Optimization scheme 2: limit the number of returned results

Using limit() to limit the size of the returned result set reduces the database server’s resource consumption and reduces the amount of data transferred over the network.

articles = db.posts.find().sort({ts:-1}).limit(10);
Copy the code

Optimization solution 3: Query only used fields, not all fields

In this case, the blog log can be very large and also include comments (as an embeded document). So it is more efficient to query only the fields in use than to query all fields:

articles = db.posts.find({}, {ts:1,title:1,author:1,abstract:1}).sort({ts:-1}).limit(10);
Copy the code

Note: You cannot update the database directly with the returned objects if only part of the field is queried. The following code is incorrect:

a_post = db.posts.findOne({}, Post.summaryFields);
a_post.x = 3;
db.posts.save(a_post);
Copy the code

Optimization Solution 4: Use capped Collection

Capped Collections are more efficient in reading and writing than regular Collections. Capped Collections are an efficient Collection type that has the following characteristics:

1, fixed size; Capped Collections must be created up front and set to size:

db.createCollection("mycoll", {capped:true, size:100000})
Copy the code

Capped Collections can be used for insert and update operations The delete operation cannot be performed. The entire Collection can only be dropped using the drop () method.

The default sort is based on Insert order. If the query is not sorted, it is always returned in insert order.

4, FIFO. If the size of the Collection is exceeded, the FIFO algorithm is used and the new record replaces the first insert record.

Optimization 5: Server Side Code Execution

Server-side Processing is similar to the stored procedures of SQL databases. Server-side Processing reduces the overhead of network communication.

Optimization 6: Hint

In general, the MongoDB Query Optimizer works well, but there are cases where hint() can be used to improve the efficiency of the operation. Hint can force a query operation to use an index. For example, if you want to query the value of multiple fields, you can use hint if there is an index on one of them:

db.collection.find({user:u, foo:d}).hint({user:1});
Copy the code

Optimization 7: Use Profiling

The Profiling feature can certainly affect efficiency, but it is not significant because it is recorded using system.profile, The System. Profile is a capped collection which has operational limitations and features, but is more efficient.