@pipe<EOL>def sort(fields):
from pymongo import ASCENDING, DESCENDING<EOL>from bson import SON<EOL>if isinstance(fields, str):<EOL><INDENT>fields = [fields]<EOL><DEDENT>if not hasattr(fields, '<STR_LIT>'):<EOL><INDENT>raise ValueError("<STR_LIT>".format(type(fields)))<EOL><DEDENT>sort = []<EOL>for field in fields:<EOL><INDENT>if field.startswith('<STR_LIT:->'):<EOL><INDENT>field = field[<NUM_LIT:1>:]<EOL>sort.append((field, DESCENDING))<EOL>continue<EOL><DEDENT>elif field.startswith('<STR_LIT:+>'):<EOL><INDENT>field = field[<NUM_LIT:1>:]<EOL><DEDENT>sort.append((field, ASCENDING))<EOL><DEDENT>return {'<STR_LIT>': SON(sort)}<EOL>
Gets a list of <fields> to sort by.
Also supports getting a single string for sorting by one field.
Reverse sort is supported by appending '-' to the field name.
Example: sort(['age', '-height']) will sort by ascending age and descending height.