TODO: Database Optimization Paging
The example of this article is based on the MongoDB database, other databases can also be extrapolate to optimize.
Paging using in MongoDB
A.skip (n) skips the first n matching documents;
B.limit (m) returns the m result, if the result of the match is less than m, the result of matching data is returned, and M is the specified upper number, not the lower number;
C.sort ({"Name": 1, "Address":-1}), 1 means ascending,-1 means descending.
Skipping a small number of documents with skip is also possible. But with a lot of data, skip will become very slow, and every database will have this, so try to avoid too much use of skip. So what do we do with paging, we can use the last result to calculate the next query.
1. Paging using Skip
Page1 = Db.user.find ({}). Limit (100)
Page2 = Db.user.find ({}). Skip (+). Limit (100)
Page3 = Db.user.find ({}). Skip ($). Limit (100)
2. Use the last result to calculate the next query, sorted by timestamp (timestamp)
Get first page
Page1 = Db.user.find ({}). sort ({"timestamp":-1}). Limit (10)
Gets the timestamp of the last record of the current page Lasttimestamp,
Query the next page of data according to Lasttimestamp
Nextpage=db.user.find ({"timestamp": {"$GT": Lasttimestamp}}). sort ({"timestamp":-1}). Limit (10)
This way, the query does not use skip, but make sure that the timestamp unique constraint ensures that the data in the document does not have the same value.
Wxgzh:ludong86
TODO: Database Optimization Paging