Difference between revisions of "Sort"
From NoSQLZoo
Line 1: | Line 1: | ||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
{{TopTenTips}} | {{TopTenTips}} | ||
<div style="min-height:25em"> | <div style="min-height:25em"> | ||
Line 25: | Line 9: | ||
<div class="q nonum" data-lang="py3">Sort all the documents in world by continent descending, then name ascending. Show only name and continent. | <div class="q nonum" data-lang="py3">Sort all the documents in world by continent descending, then name ascending. Show only name and continent. | ||
<pre class=def> | <pre class=def> | ||
− | + | db.world.find({},{name:1,continent:1,_id:0}).sort([("continent",-1),("name",1)]) | |
− | |||
− | |||
</pre> | </pre> | ||
</div> | </div> |
Revision as of 15:22, 3 December 2015
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 continent descending, then name ascending. Show only name and continent.
db.world.find({},{name:1,continent:1,_id:0}).sort([("continent",-1),("name",1)])