Sort: Difference between revisions
From NoSQLZoo
No edit summary |
No edit summary |
||
| Line 20: | Line 20: | ||
The aggregation framework provides the <code>$sort</code> operator, and <code>map_reduce</code> takes sort as a parameter that is applied to the input documents.<br/><br/> | The aggregation framework provides the <code>$sort</code> operator, and <code>map_reduce</code> takes sort as a parameter that is applied to the input documents.<br/><br/> | ||
The syntax for <code>sort()</code> is <code>sort(<field>:<value>)</code> where 1 indicates ascending and -1 indicates descending.<br/> | The syntax for <code>sort()</code> is <code>sort(<field>:<value>)</code> where 1 indicates ascending and -1 indicates descending.<br/> | ||
The order in which fields are specified dictates which fields are sorted first. | The order in which fields are specified dictates which fields are sorted first.<br/><br/> | ||
Python does not store key order for dicts, so instead of the mongo shell <code>{<field1>:<value>,<field2>:<value>}</code> use <code>[(<field1>,<value>), (<field2>,<value>)]</code> | |||
</div> | </div> | ||
| Line 26: | Line 27: | ||
<pre class=def> | <pre class=def> | ||
pp.pprint(list( | pp.pprint(list( | ||
db.world.find().sort( | db.world.find().sort([("population",-1),("name",1)]) | ||
)) | )) | ||
</pre> | </pre> | ||
</div> | </div> | ||
Revision as of 13:42, 27 July 2015
#ENCODING
import io
import sys
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-16')
#MONGO
from pymongo import MongoClient
client = MongoClient()
client.progzoo.authenticate('scott','tiger')
db = client['progzoo']
#PRETTY
import pprint
pp = pprint.PrettyPrinter(indent=4)
#CODE
from bson.code import Code
sort() is a cursor method that orders the results of a query.
The aggregation framework provides the $sort operator, and map_reduce takes sort as a parameter that is applied to the input documents.
The syntax for sort() is sort(<field>:<value>) where 1 indicates ascending and -1 indicates descending.
The order in which fields are specified dictates which fields are sorted first.
Python does not store key order for dicts, so instead of the mongo shell {<field1>:<value>,<field2>:<value>} use [(<field1>,<value>), (<field2>,<value>)]
Sort all the documents in world by population descending, then name ascending.
pp.pprint(list(
db.world.find().sort([("population",-1),("name",1)])
))