3: Try to fetch data in a single query

Keep in mind that the goal is one query, not one document, per page: sometimes we
might return multiple documents or portions of documents (not every field).


利用blog的帖子来举例子,如果某个帖子被回了10次,那么不是走10次query,而是走一次query,然后利用分页获取后面的数据,这里提到了利用一个时间字段做大于比较而不是利用mongoDB的skip特性。

 When we want to display a page, we’ll do the query:
> db.posts.find({"threadId" : id}).sort({"date" : 1}).limit(20)
Then, when we want to get the next page of messages, we’ll query for the next 20
messages on that thread, then the 20 after that, etc.:
> db.posts.find({"threadId" : id, "date" : {"$gt" : latestDateSeen}}).sort(
... {"date" : 1}).limit(20)
Then we could put an index on {threadId : 1, date : 1} to get good performance on
these queries.

We don’t use skip(20), as ranges work better for pagination.

Paging Costs
Unfortunately skip can be (very) costly and requires the server to walk from the beginning of the collection, or index, to get to the offset/skip position before it can start returning the page of data (limit). As the page number increases skip will become slower and more cpu intensive, and possibly IO bound, with larger collections.

Range based paging provides better use of indexes but does not allow you to easily jump to a specific page.


你可能感兴趣的:(thread,mongodb,Blog,performance)