📅  最后修改于: 2020-11-23 00:57:30             🧑  作者: Mango
在MongoDB中,sort()方法用于对集合中的文档进行排序。此方法接受包含字段列表及其排序顺序的文档。
排序顺序指定为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()方法以升序显示文档。如果未指定排序首选项,它将以升序显示文档。