unstable sort
$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
$sortstage has the following prototype form:copycopied{ $sort: { <field1>: <sort order>, <field2>: <sort order> ... } }$sorttakes 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 1Sort ascending. -1Sort descending. { $meta: "textScore" }Sort by the computed textScoremetadata 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:
- a 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:
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:
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:
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
$sortstage has the following prototype form:copycopied{ $sort: { <field1>: <sort order>, <field2>: <sort order> ... } }$sorttakes 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 1Sort ascending. -1Sort descending. { $meta: "textScore" }Sort by the computed textScoremetadata 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:
- a 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:
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:
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:
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的更多相关文章
- [算法]——归并排序(Merge Sort)
归并排序(Merge Sort)与快速排序思想类似:将待排序数据分成两部分,继续将两个子部分进行递归的归并排序:然后将已经有序的两个子部分进行合并,最终完成排序.其时间复杂度与快速排序均为O(nlog ...
- c#: List.Sort()实现稳固排序(stable sort)
1. 源起: KV 7.0加入列表管理功能,处理排序问题时,对空列表执行按大小.日期.长度排序发现,其中次序会发生改变,令人纳闷. 没天理呀,不应该啊!List.Sort()方法,它为什么? 对此问题 ...
- 汤姆大叔 深入理解JavaScript系列(20):《你真懂JavaScript吗?》答案详解 后六道题答案
原题目地址:http://www.cnblogs.com/TomXu/archive/2012/02/10/2342098.html 答案丰富多彩.我只是记录下自己思考了半天全部的答案. 题目一:找出 ...
- 排序算法(sorting)
学习到的排序算法的总结,包括对COMP20003中排序部分进行总结,部分图片来自COMP20003 有部分内容来自http://www.cnblogs.com/eniac12/p/5329396.ht ...
- ruby 可枚举模块Enumerable
Enumerable模块提供了遍历,搜索,比较,排序等方法.如果我们自定义的类需要实现这些方法,必须实现一个each方法.如果需要使用max,min,sort等方法,因为这些方法是集合的元素之间的排序 ...
- C++堆排序算法的实现
堆排序(Heap sort)是指利用堆这种数据结构所设计的一种排序算法.堆积是一个近似完全二叉树的结构,并同时满足堆积的性质:即子结点的键值或索引总是小于(或者大于)它的父节点.堆排序可以用到上一次的 ...
- js的6道基础题(笔试常考题)
转载:http://www.bubuko.com/infodetail-20477.html 题目一:找出数字数组中最大的元素 var arr=[0,1,2,3,4,5,6,7,8,9]; c ...
- CF1213F Unstable String Sort(差分)
其实全部可以为同一种字符串,但题目要求\(k\)种,我们考虑开始尽可能不同,最后再取\(min\) 考虑\(A\),全部不同:再做\(B\),\(S[b_{i-1}]\le S[b_{i}]\)如果开 ...
- Codeforces 1213F Unstable String Sort
cf题面 中文题意 求一个由最多26个.最少k个小写字母构成的,长度为n的字符串,这个字符串要满足的要求是--当其中字母按照p和q两个\(1\)~\(n\)的全排列重新排序时,新的字符串是按照升序排好 ...
随机推荐
- 【官方免费】Apple Silicon M1 + Parallels 16技术预览版 + Win 10 arm64
期待了好久,终于能用pd运行win10了,其实也就想写个c++,mac上配置个c++编译器太麻烦了.. 步骤: 打开 https://my.parallels.com/desktop/beta,这里下 ...
- [LeetCode]652. Find Duplicate Subtrees找到重复树
核心思想是:序列化树 序列化后,用String可以唯一的代表一棵树,其实就是前序遍历改造一下(空节点用符号表示): 一边序列化,一边用哈希表记录有没有重复的,如果有就添加,注意不能重复添加. 重点就是 ...
- [LeetCode]100. Same Tree判断树相同
dfs遍历一下判断 public boolean isSameTree(TreeNode p, TreeNode q) { if (p==null) { return q == null; } els ...
- python图片的读取保存
#coding:utf-8 from PIL import Image import matplotlib.pyplot as plt img=Image.open("F:\\Upan\\源 ...
- Java生成窗口
//字符串数组转变成int数组ints[i] = Integer.parseInt(str_string[i]);//设置窗口关闭Frame.addWindowListener(new WindowA ...
- Java JVM——8.堆
堆的核心概念 堆针对一个 JVM 进程来说是唯一的,也就是一个进程只有一个JVM,但是进程包含多个线程,他们是共享同一堆空间的. 一个JVM实例只存在一个堆内存,堆也是Java内存管理的核心区域. J ...
- Java优雅停机
Java的优雅停机通常通过注册JDK的ShootDownHook实现,当系统接受到退出指令后,首先标记系统处于退出状态,不再接受新的消息,然后将积压的消息处理完,最后调用资源回收接口将资源销毁,最后各 ...
- Spring Boot Starters
Spring Boot Starters 摘自 https://www.nosuchfield.com/2017/10/15/Spring-Boot-Starters/ 2017-10-15 Spri ...
- UNION An Unreferenced Metric for Evaluating Open-ended Story Generation精读
UNION An Unreferenced Metric for Evaluating Open-ended Story Generation精读 UNION: 一种评估开放故事生成无参考文本依赖me ...
- 推荐一款自研的Java版开源博客系统OneBlog
OneBlog 一款超好用的Java版开源博客 Introduction 简介 OneBlog 一个简洁美观.功能强大并且自适应的Java博客.使用springboot开发,前端使用Boot ...