MCPcopy Index your code
hub / github.com/mongodb/mongo-python-driver / sort

Method sort

pymongo/synchronous/cursor.py:688–734  ·  view source on GitHub ↗

Sorts this cursor's results. Pass a field name and a direction, either :data:`~pymongo.ASCENDING` or :data:`~pymongo.DESCENDING`.:: for doc in collection.find().sort('field', pymongo.ASCENDING): print(doc) To sort by multiple fields, pass a list

(
        self, key_or_list: _Hint, direction: Optional[Union[int, str]] = None
    )

Source from the content-addressed store, hash-verified

686 return self
687
688 def sort(
689 self, key_or_list: _Hint, direction: Optional[Union[int, str]] = None
690 ) -> Cursor[_DocumentType]:
691 """Sorts this cursor's results.
692
693 Pass a field name and a direction, either
694 :data:`~pymongo.ASCENDING` or :data:`~pymongo.DESCENDING`.::
695
696 for doc in collection.find().sort('field', pymongo.ASCENDING):
697 print(doc)
698
699 To sort by multiple fields, pass a list of (key, direction) pairs.
700 If just a name is given, :data:`~pymongo.ASCENDING` will be inferred::
701
702 for doc in collection.find().sort([
703 'field1',
704 ('field2', pymongo.DESCENDING)]):
705 print(doc)
706
707 Text search results can be sorted by relevance::
708
709 cursor = db.test.find(
710 {'$text': {'$search': 'some words'}},
711 {'score': {'$meta': 'textScore'}})
712
713 # Sort by 'score' field.
714 cursor.sort([('score', {'$meta': 'textScore'})])
715
716 for doc in cursor:
717 print(doc)
718
719 For more advanced text search functionality, see MongoDB's
720 `Atlas Search <https://docs.atlas.mongodb.com/atlas-search/>`_.
721
722 Raises :class:`~pymongo.errors.InvalidOperation` if this cursor has
723 already been used. Only the last :meth:`sort` applied to this
724 cursor has any effect.
725
726 :param key_or_list: a single key or a list of (key, direction)
727 pairs specifying the keys to sort on
728 :param direction: only used if `key_or_list` is a single
729 key, if not given :data:`~pymongo.ASCENDING` is assumed
730 """
731 self._check_okay_to_chain()
732 keys = helpers_shared._index_list(key_or_list, direction)
733 self._ordering = helpers_shared._index_document(keys)
734 return self
735
736 def explain(self) -> _DocumentType:
737 """Returns an explain plan record for this cursor.

Callers 15

get_versionMethod · 0.45
get_versionMethod · 0.45
test_gridfs_findMethod · 0.45
test_dict_hints_sortMethod · 0.45
test_mongosMethod · 0.45
test_index_textMethod · 0.45
test_field_selectionMethod · 0.45
test_large_limitMethod · 0.45
test_distinctMethod · 0.45
test_sortMethod · 0.45

Calls 1

_check_okay_to_chainMethod · 0.95

Tested by 15

test_gridfs_findMethod · 0.36
test_dict_hints_sortMethod · 0.36
test_mongosMethod · 0.36
test_index_textMethod · 0.36
test_field_selectionMethod · 0.36
test_large_limitMethod · 0.36
test_distinctMethod · 0.36
test_sortMethod · 0.36
test_distinctMethod · 0.36
test_to_list_tailableMethod · 0.36
test_find_rawMethod · 0.36