本文继续探讨对文档数组类型字段进行更新。可以思考平时是否遇到这样的需求。数据插入数组字段后,需要对数组字段进行排序。比如找出昨天温度最高的几个城市,或者降水量最多的几个城市。或者成绩最高的几个同学。这里都需要使用到排序。Mongodb在$push操作中,提供了$sort数据修饰符,允许用户向数组插入元素后,对数组进行排序。
定义
$sort方法在$push操作过程中,修改数组元素的排序。$sort方法,必须和$each共同使用。mongodb允许用户传递一个空的数组给$each方法,保证用户无须向数组中插入元素也可以将数组进行排序。$sort方法,按照下面的形式来使用。
1 2 3 4 5 6 7 8 |
|
对于sort specification, 当对非文档数组进行排序,或对整个文档作为整体进行排序时,正序可以指定1, 倒序可以指定为-1.当对文档字段进行排序时,指定要排序的字段和排列顺序。不需要添加数组字段的字段名称。
行为
- 自mongodb5.0开始,UPDATE操作按照字段名称的字典顺序更新字段。当字段中包含数字时,按照数字顺序依次更新字段。当然,对一个文档的多个字段操作,是原子性的。
- $sort可以对数组中的文档进行排序。这种排序可以发生在整个文档或者文档的部分字段当中。
- $sort方法必须和$each方法共同使用,否则报错
应用
对数组中的文档进行排序
向students集合中插入数据,其中quzzes是文档数组类型字段。
1 2 3 4 5 6 7 8 9 |
|
构建更新语句,要求向quzzes插入数组元素,并按照score正序进行排序。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
查看数据更新结果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
|
使用$sort排列非文档数据类型。
向students集合插入数据。其中test字段是数值类型的数组。
1 2 3 4 5 6 |
|
更新插入的数据, 要求插入新数据40, 60并对数组按照正序进行排序。
1 2 3 4 5 6 7 8 9 10 |
|
查看数据更新结果
1 2 3 4 5 6 7 8 9 10 11 12 |
|
仅使用$sort对数组进行排序
向students集合插入数据,其中tests是数值类型的数组
1 2 3 |
|
修改新插入的文档,要求将tests字段按照倒序排序。
1 2 3 4 5 6 7 8 9 10 |
|
查看更新后的结果
{
"_id": 3,
"tests": [
100,
89,
70,
20
]
}
以上就是Mongodb UPDATE使用$sort将数组重新排序的示例代码的详细内容l了。