Difference between revisions of "Sort"
From NoSQLZoo
m |
|||
(9 intermediate revisions by 2 users not shown) | |||
Line 1: | Line 1: | ||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
{{TopTenTips}} | {{TopTenTips}} | ||
− | <div style="height:25em"> | + | <div style="min-height:25em"> |
<code>sort()</code> is a cursor method that orders the results of a query.<br/> | <code>sort()</code> is a cursor method that orders the results of a query.<br/> | ||
− | The aggregation framework provides the <code>$sort</code> operator, and <code> | + | The aggregation framework provides the <code>$sort</code> operator, and <code>mapReduce</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>, <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.<br/><br/> | The order in which fields are specified dictates which fields are sorted first.<br/><br/> | ||
− | |||
− | |||
</div> | </div> | ||
− | <div class=q data-lang=" | + | <div class="q nonum" data-lang="mongo">Sort all the documents in world by continent descending, then name ascending. Show only name and continent. |
− | <pre class=def> | + | <pre class="def"><nowiki>db.world.find({}, {name: 1, continent: 1 ,_id: 0}).sort({"continent": -1, "name": 1});</nowiki></pre> |
− | |||
− | |||
− | |||
− | </pre> | ||
</div> | </div> |
Latest revision as of 16:38, 18 July 2018
sort()
is a cursor method that orders the results of a query.
The aggregation framework provides the $sort
operator, and mapReduce
takes sort as a parameter that is applied to the input documents.
The syntax for sort()
is sort({<field>:<value>, <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 continent descending, then name ascending. Show only name and continent.
db.world.find({}, {name: 1, continent: 1 ,_id: 0}).sort({"continent": -1, "name": 1});