$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. 【mybatis-plus】CRUD必备良药,mybatis的好搭档

    做开发,免不了对数据进行增删改查,那么mybatis-plus我觉得很适合我这个java新手,简单好用. 官网在这 一.什么是mybatis-plus MyBatis-Plus(简称 MP),是一个M ...

  2. Java通过IO流输出文件目录

    //通过IO流输出文件目录,不同级的目录之间用*间隔 1 package com.fjnu.io; 2 3 import java.io.File; 4 5 public class dicOut { ...

  3. Mac 上使用 Shell 脚本 + adb shell 实现简单的 Android 模拟点击自动化测试

    需求 在 A 界面,点击跳转到 B 界面(该界面会执行一些业务),再点击返回键出现 Dialog 弹窗,点击确认退出按钮,返回 A 界面.不断循环. 思路 一开始想到的就是按键精灵,下了 mac 版使 ...

  4. char*,const char*和string 互转

    1. string转const char* 1 string s = "abc"; 2 const char* c_s = s.c_str(); 2. const char*转st ...

  5. 在项目中随手把haseMap改成了currenHaseMap差点被公司给开除了。

    前言 在项目中随手把haseMap改成了currenHaseMap差点被公司给开除了. 判断相等 字符串判断相等 String str1 = null; String str2 = "jav ...

  6. 安装git之后,桌面出现蓝色问号的解决方法

    安装了git之后,桌面的图标全部变成蓝色的问号. 把隐藏的文件全部显示,也没有在桌面找到.git的文件, 解决步骤: 1.把隐藏的文件全部显示: 工具-文件夹选项-查看在"隐藏文件和文件夹& ...

  7. ESXi 中重新启动管理代理

    使用直接控制台用户界面 (DCUI)重启管理代理: 连接到您的 ESXi 主机的控制台. 按 F2 自定义系统. 以 root 身份登录. 使用上下箭头导航至故障排除选项>重新启动管理代理. 按 ...

  8. Hadoop之WordCount

    求平均数是MapReduce比较常见的算法,求平均数的算法也比较简单,一种思路是Map端读取数据,在数据输入到Reduce之前先经过shuffle,将map函数输出的key值相同的所有的value值形 ...

  9. C# 9 新特性 —— 增强的模式匹配

    C# 9 新特性 -- 增强的模式匹配 Intro C# 9 中进一步增强了模式匹配的用法,使得模式匹配更为强大,我们一起来了解一下吧 Sample C# 9 中增强了模式匹配的用法,增加了 and/ ...

  10. 基础设施层-Adnc.Infr.Consul

    Adnc.Infr.Consul 主要提供服务自动注册/发现以及获取配置. 项目结构 Configuration 配置中心相关共功能,主要有两个关键类 1.ConsulConfigurationPro ...