发布于 2015-09-14 15:01:11 | 153 次阅读 | 评论: 0 | 来源: 网络整理

cursor.sort(sort)
参数:
  • sort – A document whose fields specify the attributes on which to sort the result set.

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.

最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务