Cookies help us deliver our services. By using our services, you agree to our use of cookies. More information

Difference between revisions of "Sort"

From NoSQLZoo
Jump to: navigation, search
(Created page with "<pre class=setup> #ENCODING import io import sys sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-16') #MONGO from pymongo import MongoClient client = MongoClien...")
 
Line 25: Line 25:
 
<div class=q data-lang="py3">Sort all the documents in world by population descending, then name ascending.
 
<div class=q data-lang="py3">Sort all the documents in world by population descending, then name ascending.
 
<pre class=def>
 
<pre class=def>
for x in db.world.find().sort({"population":-1,"name":1}):
+
for x in list(db.world.find().sort({"population":-1,"name":1})):
 
     print(x)
 
     print(x)
 
</pre>
 
</pre>
 
</div>
 
</div>

Revision as of 13:37, 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.

Sort all the documents in world by population descending, then name ascending.
for x in list(db.world.find().sort({"population":-1,"name":1})):
    print(x)