发布于 2015-09-14 15:01:11 | 171 次阅读 | 评论: 0 | 来源: 网络整理
参数: |
|
---|
Append the sort() method to a cursor to control the order that the query returns matching documents. For each field in the sort document, if the field’s corresponding value is positive, then sort() returns query results in ascending order for that attribute: if the field’s corresponding value is negative, then sort() returns query results in descending order.
注解
You must apply cursor.limit() to the cursor before retrieving any documents from the database.
Consider the following example:
db.collection.find().sort( { age: -1 } );
Here, the query returns all documents in collection sorted by the age field in descending order. Specify a value of negative one (e.g. -1), as above, to sort in descending order or a positive value (e.g. 1) to sort in ascending order.
Unless you have a index for the specified key pattern, use cursor.sort() in conjunction with cursor.limit() to avoid requiring MongoDB to perform a large, in-memory sort. cursor.limit() increases the speed and reduces the amount of memory required to return this query by way of an optimized algorithm.
警告
The sort function requires that the entire sort be able to complete within 32 megabytes. When the sort option consumes more than 32 megabytes, MongoDB will return an error. Use cursor.limit(), or create an index on the field that you’re sorting to avoid this error.
The $natural parameter returns items according to their order on disk. Consider the following query:
db.collection.find().sort( { $natural: -1 } )
This will return documents in the reverse of the order on disk. Typically, the order of documents on disks reflects insertion order, except when documents move internal because of document growth due to update operations.