1. Home
  2. MongoDB
  3. MongoDB Tutorial
  4. MongoDB – sort() method

MongoDB – sort() method

MongoDB skip() Method

Use db.collection.sort() method to used to sort documents based on key in a collection before display it. You can do two types of sorting.

Syntax:

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

KEY: The column name of collection.
type: Type of sorting, 1 for ascending order and -1 for descending order sorting. Use

Example – Ascending Order

For example show the documents in sorted ascending order based on user_name column from users collection.

> db.users.find().sort({user_name:1});

Output:

{ "_id" : ObjectId("59a01b2f2427abe3470644dc"), "id" : 1002, "user_name" : "jack", "name" : [ { "first_name" : "Jack" }, { "middle_name" : "" }, { "last_name" : "Daniel" } ], "email" : "[email protected]", "designation" : "Director", "location" : "California" }
{ "_id" : ObjectId("59a01e7a2427abe3470644e2"), "id" : 1004, "user_name" : "marc", "name" : [ { "first_name" : "Marc" }, { "middle_name" : "" }, { "last_name" : "Di" } ], "email" : "[email protected]", "designation" : "Sr Analyst", "location" : "Australia" }
{ "_id" : ObjectId("59a01e7a2427abe3470644e1"), "id" : 1003, "user_name" : "peter", "name" : [ { "first_name" : "Peter" }, { "middle_name" : "S" }, { "last_name" : "Jaction" } ], "email" : "[email protected]", "designation" : "Director", "location" : "California" }
{ "_id" : ObjectId("59a01b102427abe3470644db"), "id" : 1001, "user_name" : "rahul", "name" : [ { "first_name" : "Rahul" }, { "middle_name" : "" }, { "last_name" : "Kumar" } ], "email" : "[email protected]", "designation" : "Founder and CEO", "location" : "India" }

Example – Descending Order

To show the documents in sorted descending order based on user_name column from users collection.

> db.users.find().sort({user_name:-1});

Output:

{ "_id" : ObjectId("59a01b102427abe3470644db"), "id" : 1001, "user_name" : "rahul", "name" : [ { "first_name" : "Rahul" }, { "middle_name" : "" }, { "last_name" : "Kumar" } ], "email" : "[email protected]", "designation" : "Founder and CEO", "location" : "India" }
{ "_id" : ObjectId("59a01e7a2427abe3470644e1"), "id" : 1003, "user_name" : "peter", "name" : [ { "first_name" : "Peter" }, { "middle_name" : "S" }, { "last_name" : "Jaction" } ], "email" : "[email protected]", "designation" : "Director", "location" : "California" }
{ "_id" : ObjectId("59a01e7a2427abe3470644e2"), "id" : 1004, "user_name" : "marc", "name" : [ { "first_name" : "Marc" }, { "middle_name" : "" }, { "last_name" : "Di" } ], "email" : "[email protected]", "designation" : "Sr Analyst", "location" : "Australia" }
{ "_id" : ObjectId("59a01b2f2427abe3470644dc"), "id" : 1002, "user_name" : "jack", "name" : [ { "first_name" : "Jack" }, { "middle_name" : "" }, { "last_name" : "Daniel" } ], "email" : "[email protected]", "designation" : "Director", "location" : "California" }
Was this article helpful to you? Yes 2 No 1
Advertisement