Cheap VPS & Xen Server


Residential Proxy Network - Hourly & Monthly Packages

MongoDB sort()


In MongoDB, sort() method is used to sort the documents in the collection. This method accepts a document containing list of fields along with their sorting order.

The sorting order is specified as 1 or -1.

  • 1 is used for ascending order sorting.
  • -1 is used for descending order sorting.

Syntax:

  1. db.COLLECTION_NAME.find().sort({KEY:1})

Scenario

Consider an example which has a collection name Kreationnext.

This collection has following fields within it.

  1. [
  2.   {
  3.     Course: “Java”,
  4.     details: { Duration: “6 months”, Trainer: “Sonoo Jaiswal” },
  5.     Batch: [ { size“Medium”, qty: 25 } ],
  6.     category: “Programming Language”
  7.   },
  8.   {
  9.     Course: “.Net”,
  10.     details: { Duration: “6 months”, Trainer: “Prashant Verma” },
  11.     Batch: [ { size“Small”, qty: 5 }, { size“Medium”, qty: 10 }, ],
  12.     category: “Programming Language”
  13.   },
  14.   {
  15.     Course: “Web Designing”,
  16.     details: { Duration: “3 months”, Trainer: “Rashmi Desai” },
  17.     Batch: [ { size“Small”, qty: 5 }, { size“Large”, qty: 10 } ],
  18.     category: “Programming Language”
  19.   }
  20. ];

Execute the following query to display the documents in descending order.

  1. db.Kreationnext.find().sort({“Course”:-1})

This will show the documents in descending order.

{ "_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" }

Note: By default sort() method displays the documents in ascending order. If you don’t specify the sorting preference, it will display documents in ascending order.

Comments

comments