本文继续探讨对文档数组类型字段进行更新。可以思考平时是否遇到这样的需求。数据插入数组字段后,需要对数组字段进行排序。比如找出昨天温度最高的几个城市,或者降水量最多的几个城市。或者成绩最高的几个同学。这里都需要使用到排序。Mongodb在$push操作中,提供了$sort数据修饰符,允许用户向数组插入元素后,对数组进行排序。


定义

$sort方法在$push操作过程中,修改数组元素的排序。$sort方法,必须和$each共同使用。mongodb允许用户传递一个空的数组给$each方法,保证用户无须向数组中插入元素也可以将数组进行排序。$sort方法,按照下面的形式来使用。

1

2

3

4

5

6

7

8


{

$push: {

<field>: {

$each: [<value1>, <value2>, ...],

$sort: <sort specification>

}

}

}


对于sort specification, 当对非文档数组进行排序,或对整个文档作为整体进行排序时,正序可以指定1, 倒序可以指定为-1.当对文档字段进行排序时,指定要排序的字段和排列顺序。不需要添加数组字段的字段名称。


行为

  • 自mongodb5.0开始,UPDATE操作按照字段名称的字典顺序更新字段。当字段中包含数字时,按照数字顺序依次更新字段。当然,对一个文档的多个字段操作,是原子性的。
  • $sort可以对数组中的文档进行排序。这种排序可以发生在整个文档或者文档的部分字段当中。
  • $sort方法必须和$each方法共同使用,否则报错


应用


对数组中的文档进行排序

向students集合中插入数据,其中quzzes是文档数组类型字段。

1

2

3

4

5

6

7

8

9


db.students.insertOne(

{

_id:1,

quzzes: [

{id:1, score:6},

{id:2, score:9}

]

}

)


构建更新语句,要求向quzzes插入数组元素,并按照score正序进行排序。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15


db.students.updateOne(

{_id:1},

{

$push: {

quzzes: {

$each: [

{id:3, score:8},

{id:4, score:7},

{id:5, score:6}

],

$sort: {score:1}

}

}

}

)


查看数据更新结果

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


db.students.find().pretty();

[

{

"_id": 1,

"quzzes": [

{

"id": 1,

"score": 6

},

{

"id": 5,

"score": 6

},

{

"id": 4,

"score": 7

},

{

"id": 3,

"score": 8

},

{

"id": 2,

"score": 9

}

]

}

]



使用$sort排列非文档数据类型。

向students集合插入数据。其中test字段是数值类型的数组。

1

2

3

4

5

6


db.students.insertOne({

_id:2,

tests: [

89,70,89, 50

]

})


更新插入的数据, 要求插入新数据40, 60并对数组按照正序进行排序。

1

2

3

4

5

6

7

8

9

10


db.students.updateOne({

_id:2

},{

$push: {

tests: {

$each: [40, 60],

$sort: 1

}

}

})


查看数据更新结果

1

2

3

4

5

6

7

8

9

10

11

12


db.students.find()

{

"_id": 2,

"tests": [

40,

50,

60,

70,

89,

89

]

}



仅使用$sort对数组进行排序

向students集合插入数据,其中tests是数值类型的数组

1

2

3


db.students.insertOne({

_id:3, tests: [89, 70, 100, 20]

})


修改新插入的文档,要求将tests字段按照倒序排序。

1

2

3

4

5

6

7

8

9

10


db.students.updateOne({

_id:3

},{

$push: {

tests: {

$each: [],

$sort: -1

}

}

})


查看更新后的结果

{
    "_id": 3,
    "tests": [
      100,
      89,
      70,
      20
    ]
  }

以上就是Mongodb UPDATE使用$sort将数组重新排序的示例代码的详细内容l了。