Skip to content
Permalink
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
228 lines (155 sloc) 7.25 KB
=============
cursor.sort()
=============
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. method:: cursor.sort(sort)
Specifies the order in which the query returns matching documents.
You must apply :method:`~cursor.sort()` to the cursor before
retrieving any documents from the database.
The :method:`~cursor.sort()` method has the following parameter:
.. include:: /includes/apiargs/method-cursor.sort-param.rst
The ``sort`` parameter contains field and value pairs, in the
following form:
.. code-block:: javascript
{ field: value }
The sort document can specify :ref:`ascending or descending sort on
existing fields <sort-asc-desc>` or :ref:`sort on computed metadata
<sort-metadata>`.
Behaviors
---------
Result Ordering
~~~~~~~~~~~~~~~
Unless you specify the :method:`~cursor.sort()` method or use the
:query:`$near` operator, MongoDB does **not** guarantee the order of
query results.
.. _sort-asc-desc:
Ascending/Descending Sort
~~~~~~~~~~~~~~~~~~~~~~~~~
Specify in the sort parameter the field or fields to sort by and a
value of ``1`` or ``-1`` to specify an ascending or descending sort
respectively.
The following sample document specifies a descending sort by the
``age`` field and then an ascending sort by the ``posts`` field:
.. code-block:: javascript
{ age : -1, posts: 1 }
.. include:: /includes/fact-sort-order.rst
For details on the comparison/sort order for specific types, see
:ref:`bson-types-comparison-order`.
.. _sort-metadata:
Metadata Sort
~~~~~~~~~~~~~
Specify in the sort parameter a new field name for the
computed metadata and specify the :projection:`$meta` expression as its
value.
The following sample document specifies a descending sort by the
``"textScore"`` metadata:
.. code-block:: javascript
{ score: { $meta: "textScore" } }
The specified metadata determines the sort order. For example, the
``"textScore"`` metadata sorts in descending order. See
:projection:`$meta` for details.
Restrictions
~~~~~~~~~~~~
When unable to obtain the sort order from an index, MongoDB will sort
the results in memory, which requires that the result set being sorted
is less than 32 megabytes.
When the sort operation consumes more than 32 megabytes, MongoDB
returns an error. To avoid this error, either create an index
supporting the sort operation (see :ref:`sort-index-use`) or use
:method:`~cursor.sort()` in conjunction with :method:`~cursor.limit()`
(see :ref:`sort-limit-results`).
.. _sort-index-use:
Sort and Index Use
~~~~~~~~~~~~~~~~~~
The sort can sometimes be satisfied by scanning an index in order. If
the query plan uses an index to provide the requested sort order,
MongoDB does not perform an in-memory sorting of the result set. For
more information, see :doc:`/tutorial/sort-results-with-indexes`.
.. _sort-limit-results:
Limit Results
~~~~~~~~~~~~~
You can use :method:`~cursor.sort()` in conjunction with
:method:`~cursor.limit()` to return the first (in terms of the sort
order) ``k`` documents, where ``k`` is the specified limit.
If MongoDB cannot obtain the sort order via an index scan, then MongoDB
uses a top-k sort algorithm. This algorithm buffers the first ``k``
results (or last, depending on the sort order) seen so far by the
underlying index or collection access. If at any point the memory
footprint of these ``k`` results exceeds 32 megabytes, the query will
fail.
.. _sort-with-projection:
Interaction with :term:`Projection`
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When a set of results are both sorted and projected, the MongoDB query engine
will always apply the sorting **first**.
Examples
--------
A collection ``orders`` contain the following documents:
.. code-block:: javascript
{ _id: 1, item: { category: "cake", type: "chiffon" }, amount: 10 }
{ _id: 2, item: { category: "cookies", type: "chocolate chip" }, amount: 50 }
{ _id: 3, item: { category: "cookies", type: "chocolate chip" }, amount: 15 }
{ _id: 4, item: { category: "cake", type: "lemon" }, amount: 30 }
{ _id: 5, item: { category: "cake", type: "carrot" }, amount: 20 }
{ _id: 6, item: { category: "brownies", type: "blondie" }, amount: 10 }
The following query, which returns all documents from the ``orders``
collection, does not specify a sort order:
.. code-block:: javascript
db.orders.find()
The query returns the documents in indeterminate order:
.. code-block:: none
{ "_id" : 1, "item" : { "category" : "cake", "type" : "chiffon" }, "amount" : 10 }
{ "_id" : 2, "item" : { "category" : "cookies", "type" : "chocolate chip" }, "amount" : 50 }
{ "_id" : 3, "item" : { "category" : "cookies", "type" : "chocolate chip" }, "amount" : 15 }
{ "_id" : 4, "item" : { "category" : "cake", "type" : "lemon" }, "amount" : 30 }
{ "_id" : 5, "item" : { "category" : "cake", "type" : "carrot" }, "amount" : 20 }
{ "_id" : 6, "item" : { "category" : "brownies", "type" : "blondie" }, "amount" : 10 }
The following query specifies a sort on the ``amount`` field in
descending order.
.. code-block:: javascript
db.orders.find().sort( { amount: -1 } )
The query returns the following documents, in descending order of
``amount``:
.. code-block:: javascript
{ "_id" : 2, "item" : { "category" : "cookies", "type" : "chocolate chip" }, "amount" : 50 }
{ "_id" : 4, "item" : { "category" : "cake", "type" : "lemon" }, "amount" : 30 }
{ "_id" : 5, "item" : { "category" : "cake", "type" : "carrot" }, "amount" : 20 }
{ "_id" : 3, "item" : { "category" : "cookies", "type" : "chocolate chip" }, "amount" : 15 }
{ "_id" : 1, "item" : { "category" : "cake", "type" : "chiffon" }, "amount" : 10 }
{ "_id" : 6, "item" : { "category" : "brownies", "type" : "blondie" }, "amount" : 10 }
The following query specifies the sort order using the fields from an
embedded document ``item``. The query sorts first by the ``category`` field
in ascending order, and then within each ``category``, by the ``type``
field in ascending order.
.. code-block:: javascript
db.orders.find().sort( { "item.category": 1, "item.type": 1 } )
The query returns the following documents, ordered first by the
``category`` field, and within each category, by the ``type`` field:
.. code-block:: javascript
{ "_id" : 6, "item" : { "category" : "brownies", "type" : "blondie" }, "amount" : 10 }
{ "_id" : 5, "item" : { "category" : "cake", "type" : "carrot" }, "amount" : 20 }
{ "_id" : 1, "item" : { "category" : "cake", "type" : "chiffon" }, "amount" : 10 }
{ "_id" : 4, "item" : { "category" : "cake", "type" : "lemon" }, "amount" : 30 }
{ "_id" : 2, "item" : { "category" : "cookies", "type" : "chocolate chip" }, "amount" : 50 }
{ "_id" : 3, "item" : { "category" : "cookies", "type" : "chocolate chip" }, "amount" : 15 }
.. _return-storage-order:
.. _return-natural-order:
Return in Natural Order
-----------------------
The :operator:`$natural` parameter returns items according to their
:term:`natural order` within the database. This ordering is an internal
implementation feature, and you should not rely on any particular structure
within it.
.. note::
.. include:: /includes/extracts/views-unsupported-natural-sort.rst
Index Use
~~~~~~~~~
.. include:: /includes/fact-natural-parameter.rst
.. seealso:: :operator:`$natural`
You can’t perform that action at this time.