Skip to content

Commit 7642ea2

Browse files
committed
More detailed examples for Cursor.sort, PYTHON-663.
1 parent e2ef986 commit 7642ea2

File tree

1 file changed

+27
-6
lines changed

1 file changed

+27
-6
lines changed

pymongo/cursor.py

Lines changed: 27 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -642,12 +642,33 @@ def min(self, spec):
642642
def sort(self, key_or_list, direction=None):
643643
"""Sorts this cursor's results.
644644
645-
Takes either a single key and a direction, or a list of (key,
646-
direction) pairs. The key(s) must be an instance of ``(str,
647-
unicode)``, and the direction(s) must be one of
648-
(:data:`~pymongo.ASCENDING`,
649-
:data:`~pymongo.DESCENDING`). Raises
650-
:class:`~pymongo.errors.InvalidOperation` if this cursor has
645+
Pass a field name and a direction, either
646+
:data:`~pymongo.ASCENDING` or :data:`~pymongo.DESCENDING`::
647+
648+
for doc in collection.find().sort('field', pymongo.ASCENDING):
649+
print(doc)
650+
651+
To sort by multiple fields, pass a list of (key, direction) pairs::
652+
653+
for doc in collection.find().sort([
654+
('field1', pymongo.ASCENDING),
655+
('field2', pymongo.DESCENDING)]):
656+
print(doc)
657+
658+
Beginning with MongoDB version 2.6, text search results can be
659+
sorted by relevance::
660+
661+
cursor = db.test.find(
662+
{'$text': {'$search': 'some words'}},
663+
{'score': {'$meta': 'textScore'}})
664+
665+
# Sort by 'score' field.
666+
cursor.sort([('score', {'$meta': 'textScore'})])
667+
668+
for doc in cursor:
669+
print(doc)
670+
671+
Raises :class:`~pymongo.errors.InvalidOperation` if this cursor has
651672
already been used. Only the last :meth:`sort` applied to this
652673
cursor has any effect.
653674

0 commit comments

Comments
 (0)