$sort (aggregation) — MongoDB Manual https://docs.mongodb.com/manual/reference/operator/aggregation/sort/

Definition

$sort

Sorts all input documents and returns them to the pipeline in sorted order.

The $sort stage has the following prototype form:

copy

copied
{ $sort: { <field1>: <sort order>, <field2>: <sort order> ... } }

$sort takes a document that specifies the field(s) to sort by and the respective sort order. <sort order> can have one of the following values:

Value Description
1 Sort ascending.
-1 Sort descending.
{ $meta: "textScore" } Sort by the computed textScore metadata in descending order. See Text Score Metadata Sort for an example.

If sorting on multiple fields, sort order is evaluated from left to right. For example, in the form above, documents are first sorted by <field1>. Then documents with the same <field1> values are further sorted by <field2>.

Behavior

Sort Stability

In MongoDB, sorts are inherently stable, unless sorting on a field which contains duplicate values:

  • stable sort is one that returns the same sort order each time it is performed
  • an unstable sort is one that may return a different sort order when performed multiple times

If a stable sort is desired, include at least one field in your sort that contains exclusively unique values. The easiest way to guarantee this is to include the _id field in your sort query.

Consider the following restaurant collection:

copy

copied
db.restaurants.insertMany( [
{ "_id" : 1, "name" : "Central Park Cafe", "borough" : "Manhattan"},
{ "_id" : 2, "name" : "Rock A Feller Bar and Grill", "borough" : "Queens"},
{ "_id" : 3, "name" : "Empire State Pub", "borough" : "Brooklyn"},
{ "_id" : 4, "name" : "Stan's Pizzaria", "borough" : "Manhattan"},
{ "_id" : 5, "name" : "Jane's Deli", "borough" : "Brooklyn"},
] );

The following command uses the $sort stage to sort on the borough field:

copy

copied
db.restaurants.aggregate(
[
{ $sort : { borough : 1 } }
]
)

In this example, the sort is unstable, since the borough field contains duplicate values for both Manhattan and Brooklyn. Documents are returned in alphabetical order by borough, but the order of those documents with duplicate values for borough might not the be the same across multiple executions of the same sort. For example, here are the results from two different executions of the above command:

 
{ "_id" : 3, "name" : "Empire State Pub", "borough" : "Brooklyn" }
{ "_id" : 5, "name" : "Jane's Deli", "borough" : "Brooklyn" }
{ "_id" : 1, "name" : "Central Park Cafe", "borough" : "Manhattan" }
{ "_id" : 4, "name" : "Stan's Pizzaria", "borough" : "Manhattan" }
{ "_id" : 2, "name" : "Rock A Feller Bar and Grill", "borough" : "Queens" } { "_id" : 5, "name" : "Jane's Deli", "borough" : "Brooklyn" }
{ "_id" : 3, "name" : "Empire State Pub", "borough" : "Brooklyn" }
{ "_id" : 4, "name" : "Stan's Pizzaria", "borough" : "Manhattan" }
{ "_id" : 1, "name" : "Central Park Cafe", "borough" : "Manhattan" }
{ "_id" : 2, "name" : "Rock A Feller Bar and Grill", "borough" : "Queens" }

While the values for borough are still sorted in alphabetical order, the order of the documents containing duplicate values for borough (i.e. Manhattan and Brooklyn) is not the same.

To achieve a stable sort, add a field which contains exclusively unique values to the sort. The following command uses the $sort stage to sort on both the borough field and the _id field:

copy

copied
db.restaurants.aggregate(
[
{ $sort : { borough : 1, _id: 1 } }
]
)

Since the _id field is always guaranteed to contain exclusively unique values, the returned sort order will always be the same across multiple executions of the same sort.

Definition

$sort

Sorts all input documents and returns them to the pipeline in sorted order.

The $sort stage has the following prototype form:

copy

copied
{ $sort: { <field1>: <sort order>, <field2>: <sort order> ... } }

$sort takes a document that specifies the field(s) to sort by and the respective sort order. <sort order> can have one of the following values:

Value Description
1 Sort ascending.
-1 Sort descending.
{ $meta: "textScore" } Sort by the computed textScore metadata in descending order. See Text Score Metadata Sort for an example.

If sorting on multiple fields, sort order is evaluated from left to right. For example, in the form above, documents are first sorted by <field1>. Then documents with the same <field1> values are further sorted by <field2>.

Behavior

Sort Stability

In MongoDB, sorts are inherently stable, unless sorting on a field which contains duplicate values:

  • stable sort is one that returns the same sort order each time it is performed
  • an unstable sort is one that may return a different sort order when performed multiple times

If a stable sort is desired, include at least one field in your sort that contains exclusively unique values. The easiest way to guarantee this is to include the _id field in your sort query.

Consider the following restaurant collection:

copy

copied
db.restaurants.insertMany( [
{ "_id" : 1, "name" : "Central Park Cafe", "borough" : "Manhattan"},
{ "_id" : 2, "name" : "Rock A Feller Bar and Grill", "borough" : "Queens"},
{ "_id" : 3, "name" : "Empire State Pub", "borough" : "Brooklyn"},
{ "_id" : 4, "name" : "Stan's Pizzaria", "borough" : "Manhattan"},
{ "_id" : 5, "name" : "Jane's Deli", "borough" : "Brooklyn"},
] );

The following command uses the $sort stage to sort on the borough field:

copy

copied
db.restaurants.aggregate(
[
{ $sort : { borough : 1 } }
]
)

In this example, the sort is unstable, since the borough field contains duplicate values for both Manhattan and Brooklyn. Documents are returned in alphabetical order by borough, but the order of those documents with duplicate values for borough might not the be the same across multiple executions of the same sort. For example, here are the results from two different executions of the above command:

 
{ "_id" : 3, "name" : "Empire State Pub", "borough" : "Brooklyn" }
{ "_id" : 5, "name" : "Jane's Deli", "borough" : "Brooklyn" }
{ "_id" : 1, "name" : "Central Park Cafe", "borough" : "Manhattan" }
{ "_id" : 4, "name" : "Stan's Pizzaria", "borough" : "Manhattan" }
{ "_id" : 2, "name" : "Rock A Feller Bar and Grill", "borough" : "Queens" } { "_id" : 5, "name" : "Jane's Deli", "borough" : "Brooklyn" }
{ "_id" : 3, "name" : "Empire State Pub", "borough" : "Brooklyn" }
{ "_id" : 4, "name" : "Stan's Pizzaria", "borough" : "Manhattan" }
{ "_id" : 1, "name" : "Central Park Cafe", "borough" : "Manhattan" }
{ "_id" : 2, "name" : "Rock A Feller Bar and Grill", "borough" : "Queens" }

While the values for borough are still sorted in alphabetical order, the order of the documents containing duplicate values for borough (i.e. Manhattan and Brooklyn) is not the same.

To achieve a stable sort, add a field which contains exclusively unique values to the sort. The following command uses the $sort stage to sort on both the borough field and the _id field:

copy

copied
db.restaurants.aggregate(
[
{ $sort : { borough : 1, _id: 1 } }
]
)

Since the _id field is always guaranteed to contain exclusively unique values, the returned sort order will always be the same across multiple executions of the same sort.

unstable sort的更多相关文章

  1. [算法]——归并排序(Merge Sort)

    归并排序(Merge Sort)与快速排序思想类似:将待排序数据分成两部分,继续将两个子部分进行递归的归并排序:然后将已经有序的两个子部分进行合并,最终完成排序.其时间复杂度与快速排序均为O(nlog ...

  2. c#: List.Sort()实现稳固排序(stable sort)

    1. 源起: KV 7.0加入列表管理功能,处理排序问题时,对空列表执行按大小.日期.长度排序发现,其中次序会发生改变,令人纳闷. 没天理呀,不应该啊!List.Sort()方法,它为什么? 对此问题 ...

  3. 汤姆大叔 深入理解JavaScript系列(20):《你真懂JavaScript吗?》答案详解 后六道题答案

    原题目地址:http://www.cnblogs.com/TomXu/archive/2012/02/10/2342098.html 答案丰富多彩.我只是记录下自己思考了半天全部的答案. 题目一:找出 ...

  4. 排序算法(sorting)

    学习到的排序算法的总结,包括对COMP20003中排序部分进行总结,部分图片来自COMP20003 有部分内容来自http://www.cnblogs.com/eniac12/p/5329396.ht ...

  5. ruby 可枚举模块Enumerable

    Enumerable模块提供了遍历,搜索,比较,排序等方法.如果我们自定义的类需要实现这些方法,必须实现一个each方法.如果需要使用max,min,sort等方法,因为这些方法是集合的元素之间的排序 ...

  6. C++堆排序算法的实现

    堆排序(Heap sort)是指利用堆这种数据结构所设计的一种排序算法.堆积是一个近似完全二叉树的结构,并同时满足堆积的性质:即子结点的键值或索引总是小于(或者大于)它的父节点.堆排序可以用到上一次的 ...

  7. js的6道基础题(笔试常考题)

    转载:http://www.bubuko.com/infodetail-20477.html 题目一:找出数字数组中最大的元素   var arr=[0,1,2,3,4,5,6,7,8,9];   c ...

  8. CF1213F Unstable String Sort(差分)

    其实全部可以为同一种字符串,但题目要求\(k\)种,我们考虑开始尽可能不同,最后再取\(min\) 考虑\(A\),全部不同:再做\(B\),\(S[b_{i-1}]\le S[b_{i}]\)如果开 ...

  9. Codeforces 1213F Unstable String Sort

    cf题面 中文题意 求一个由最多26个.最少k个小写字母构成的,长度为n的字符串,这个字符串要满足的要求是--当其中字母按照p和q两个\(1\)~\(n\)的全排列重新排序时,新的字符串是按照升序排好 ...

随机推荐

  1. IIS本地部署局域网可随时访问的项目+mysql可局域网内访问

    开端口即可 或者以下 原理 在本机的IIS下创建一个网站,文件目录直接指向Web项目文件夹 步骤 1.项目的启动项目为web 2.在iis中创建一个新的网站(Work_TK_EIS) 文件目录为web ...

  2. VS批量添加多个文件

    步骤 1.设置项目,显示所有文件.2.点击项目,右键在资源管理器中打开.3.将要导入的文件复制到对应的文件中去.4.在解决方案中就可以看到刚才添加的多个文件.5.在新加的文件夹上右键,包括在项目中.

  3. java中根据后端返回的数据加载table列表

    <%//引入 js @ page language="java" pageEncoding="UTF-8"%> <!DOCTYPE HTML& ...

  4. java Swing组件随着窗口拖动等比移动或等比放大

    实现原理很简单, 1清空布局(使用绝对布局) 2添加监听器(监听窗口是否被拖动) 3在监听器里面动态调整 组件的位置 效果如下: 拖动之后效果: 代码实现: import java.awt.Event ...

  5. 「Elasticsearch」ES重建索引怎么才能做到数据无缝迁移呢?

    背景 众所周知,Elasticsearch是⼀个实时的分布式搜索引擎,为⽤户提供搜索服务.当我们决定存储某种数据,在创建索引的时候就需要将数据结构,即Mapping确定下来,于此同时索引的设定和很多固 ...

  6. 2.2.1 Sqoop1的基本架构

    当用户通过shell命令提交迁移作业后,Sqoop会从关系型数据库中读取元信息,并根据并发度和数据表大小将数据划分成若干分片,每片交给一个Map Task处理,这样多个Map Task同时读取数据库中 ...

  7. VUE项目性能优化实践——通过懒加载提升页面响应速度

    本文由葡萄城技术团队原创并首发 转载请注明出处:葡萄城官网,葡萄城为开发者提供专业的开发工具.解决方案和服务,赋能开发者. 最近我司因业务需求,需要在一个内部数据分析平台集成在线Excel功能,既然我 ...

  8. C++把数字排序

    C++把数字排序 描述 思路 代码 描述 如题,详细如下: 输入不超过1024个数字,以特殊数字结尾,如(-999),把数字从小到大排序. 思路 目前,我们有两种思路可以写: 1是 在输入的时候,排序 ...

  9. ssh信任 sftp用法 scp用法【转】

    为了进行批量关机工作,前提要配置好ssh的双机信任. A机192.168.1.241 B机192.168.1.212 在A机上获取一个pub密钥,即为公共密钥. 执行这个命令后:ssh-keygen  ...

  10. 【Java基础】集合

    集合 集合概述 一方面, 面向对象语言对事物的体现都是以对象的形式,为了方便对多个对象 的操作,就要对对象进行存储.另一方面,使用 Array 存储对象方面具有一些弊端,而 Java 集合就像一种容器 ...