MongoDB sort() 方法
在 MongoDB 中,sort() 方法用于对集合中的文档进行排序。该方法接受一个包含字段列表和排序顺序的文档作为参数。
排序顺序可以指定为 1 或 -1。
- 1 用于升序排序。
- -1 用于降序排序。
语法:
db.COLLECTION_NAME.find().sort({KEY:1})
场景
考虑一个名为javatpoint的集合的示例。
该集合中有以下字段。
[
{
Course: "Java",
details: { Duration: "6 months", Trainer: "Sonoo Jaiswal" },
Batch: [ { size: "Medium", qty: 25 } ],
category: "Programming Language"
},
{
Course: ".Net",
details: { Duration: "6 months", Trainer: "Prashant Verma" },
Batch: [ { size: "Small", qty: 5 }, { size: "Medium", qty: 10 }, ],
category: "Programming Language"
},
{
Course: "Web Designing",
details: { Duration: "3 months", Trainer: "Rashmi Desai" },
Batch: [ { size: "Small", qty: 5 }, { size: "Large", qty: 10 } ],
category: "Programming Language"
}
];
执行以下查询以按降序显示文档。
db.javatpoint.find().sort({"Course":-1})
这将按降序显示文档。
{ "_id" : ObjectId("564dbced8e2c097d15fbb603"), "Course" : "Web Designing", "det
ails" : { "Duration" : "3 months", "Trainer" : "Rashmi Desai" }, "Batch" : [ { "
size" : "Small", "qty" : 5 }, { "size" : "Large", "qty" : 10 } ], "category" : "
Programming Language" }
{ "_id" : ObjectId("564dbced8e2c097d15fbb601"), "Course" : "Java", "details" : {
"Duration" : "6 months", "Trainer" : "Sonoo Jaiswal" }, "Batch" : [ { "size" :
"Medium", "qty" : 25 } ], "category" : "Programming Language" }
{ "_id" : ObjectId("564dbced8e2c097d15fbb602"), "Course" : ".Net", "details" : {
"Duration" : "6 months", "Trainer" : "Prashant Verma" }, "Batch" : [ { "size" :
"Small", "qty" : 5 }, { "size" : "Medium", "qty" : 10 } ], "category" : "Progra
mming Language" }
注意:默认情况下,sort()方法以升序方式显示文档。如果您没有指定排序偏好,它将以升序方式显示文档。