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
)
| 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. |