MongoDB sort()方法

【MongoDB sort()方法】在MongoDB中, sort()方法用于对集合中的文档进行排序。此方法接受包含字段列表及其排序顺序的文档。
排序顺序指定为1或-1。

  • 1用于升序排序。
  • -1用于降序排序。
句法:
db.COLLECTION_NAME.find().sort({KEY:1})

情境考虑一个具有集合名称srcmini的示例。
该集合中包含以下字段。
[ { 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.srcmini.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()方法以升序显示文档。如果你未指定排序首选项, 它将以升序显示文档。

    推荐阅读