$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. inotifywait命令如何监控文件变化?

    转载自:https://segmentfault.com/a/1190000038351925 文件监控可以配合rsync实现文件自动同步,例如监听某个目录,当文件变化时,使用rsync命令将变化的文 ...

  2. Selenium Web元素操作

    我们定位到Web页面元素之后,可以对元素进行一系列的操作,实现跟页面的交互.包括点击.文本输入.元素属性获取等.常用的方法列举如下: 方法 描述 click() 点击元素 send_keys(**va ...

  3. 通过`RestTemplate`上传文件(InputStreamResource详解)

    通过RestTemplate上传文件 1.上传文件File 碰到一个需求,在代码中通过HTTP方式做一个验证的请求,请求的参数包含了文件类型.想想其实很简单,直接使用定义好的MultiValueMap ...

  4. springMVC实现定时器

    //springmvc.xml文件配置 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns ...

  5. 徐汉彬:Web系统大规模并发——电商秒杀与抢购

    摘要:电商的秒杀和抢购,从技术的角度来说,会对Web系统产生巨大的考验.本期<问底>,徐汉彬将带大家关注秒杀和抢购的技术实现和优化,同时,从技术层面揭开,为什么我们总是不容易抢到火车票的原 ...

  6. Deep Neural Networks for YouTube Recommendations YouTube的经典推荐框架

    https://zhuanlan.zhihu.com/p/52169807 王喆大佬的讲解

  7. Qt学习笔记-Qt5和Qt4在音频方面的不同-QtAV

    之前学习qt4的时候,播放音频用的是phonon播放后端插件+mplayer. 今天改用qt5了.qt5中去掉了phonon模块加了multimedia.但是依然无法播放音乐,因为没有ffmpge s ...

  8. jit编译原理

    jit用以把程序全部或部分翻译成本地机器码,当需要装载某个类[通常是创建第一个对象时],编译器会先找到其.class文件,然后将该类的字节码装入内存. hotspot采用惰性评估法: 如果一段代码频繁 ...

  9. Linux 路由 静态路由

    Linux 路由 静态路由 目录 Linux 路由 静态路由 一.临时生效,使用命令route A.添加到主机的路由 B.添加到网络的路由 C.添加默认路由 D.删除路由 E.查看所有路由信息 二.临 ...

  10. jdbc-创建statement-数量过多导致游标超限

    在循环中重复创建  java.sql.Connection.prepareStatement(sql)  , 导致游标超限