📅  最后修改于: 2023-12-03 14:44:21.392000             🧑  作者: Mango
在 MongoDB 中,$sort 修饰符是用来对查询结果进行排序的。它可以按照指定的字段进行升序或降序排序。
db.collection.find().sort({field: 1}) // 升序排序
db.collection.find().sort({field: -1}) // 降序排序
field
:要用来排序的字段名,可以是任意的有效字段名。1
:代表升序排序。-1
:代表降序排序。假设我们有下面这个集合:
db.users.insertMany([
{ name: "Tom", age: 23, salary: 10000 },
{ name: "Jack", age: 30, salary: 15000 },
{ name: "Bob", age: 25, salary: 12000 },
{ name: "Lucy", age: 27, salary: 11000 }
])
现在,我们来按照年龄做一次升序排序:
db.users.find().sort({ age: 1 })
输出结果为:
{ "_id" : ObjectId("61188c77b31cb7e178560f31"), "name" : "Tom", "age" : 23, "salary" : 10000 }
{ "_id" : ObjectId("61188c77b31cb7e178560f34"), "name" : "Bob", "age" : 25, "salary" : 12000 }
{ "_id" : ObjectId("61188c77b31cb7e178560f36"), "name" : "Lucy", "age" : 27, "salary" : 11000 }
{ "_id" : ObjectId("61188c77b31cb7e178560f32"), "name" : "Jack", "age" : 30, "salary" : 15000 }
可以看到,根据年龄做了一次升序排序,结果是按照年龄从小到大输出的。
现在,我们来按照薪资做一次降序排序:
db.users.find().sort({ salary: -1 })
输出结果为:
{ "_id" : ObjectId("61188c77b31cb7e178560f32"), "name" : "Jack", "age" : 30, "salary" : 15000 }
{ "_id" : ObjectId("61188c77b31cb7e178560f34"), "name" : "Bob", "age" : 25, "salary" : 12000 }
{ "_id" : ObjectId("61188c77b31cb7e178560f36"), "name" : "Lucy", "age" : 27, "salary" : 11000 }
{ "_id" : ObjectId("61188c77b31cb7e178560f31"), "name" : "Tom", "age" : 23, "salary" : 10000 }
可以看到,根据薪资做了一次降序排序,结果是按照薪资从大到小输出的。