Database

Sorting is a fundamental action done with databases. MongoDB has a similar function that works great.

Sort by ascending order

Use 1 as the value to sort in ascending order

> db.books.find().sort({title: 1})
{ "_id" : ObjectId("5d5e1c357545de885fa391fb"), "title" : "Book Title", "category" : "Fiction", "tags" : [ "children", "fantasy" ], "user" : { "name" : "Sophia", "status" : "author" }, "date" : "Thu Aug 22 2019 12:38:12 GMT+0800 (PST)" }
{ "_id" : ObjectId("5d5e21467545de885fa391fc"), "title" : "Book Title 2", "category" : "Fiction", "tags" : [ "teen", "fantasy" ], "user" : { "name" : "Ryan", "status" : "author" }, "date" : "Thu Aug 22 2019 12:59:50 GMT+0800 (PST)" }
{ "_id" : ObjectId("5d5e21a47545de885fa391fd"), "title" : "Book Title 3", "category" : "Non-Fiction", "tags" : [ "history", "documentary" ], "user" : { "name" : "Arthur", "status" : "author" }, "date" : "Thu Aug 22 2019 13:01:24 GMT+0800 (PST)" }
{ "_id" : ObjectId("5d5e21a47545de885fa391fe"), "title" : "Book Title 4", "category" : "Non-Fiction", "tags" : [ "legal" ], "user" : { "name" : "Manuel", "status" : "author" }, "date" : "Thu Aug 22 2019 13:01:24 GMT+0800 (PST)" }

Sort by descending order

Use -1 as the value to sort by descending order

> db.books.find().sort({title: -1})
{ "_id" : ObjectId("5d5e21a47545de885fa391fe"), "title" : "Book Title 4", "category" : "Non-Fiction", "tags" : [ "legal" ], "user" : { "name" : "Manuel", "status" : "author" }, "date" : "Thu Aug 22 2019 13:01:24 GMT+0800 (PST)" }
{ "_id" : ObjectId("5d5e21a47545de885fa391fd"), "title" : "Book Title 3", "category" : "Non-Fiction", "tags" : [ "history", "documentary" ], "user" : { "name" : "Arthur", "status" : "author" }, "date" : "Thu Aug 22 2019 13:01:24 GMT+0800 (PST)" }
{ "_id" : ObjectId("5d5e21467545de885fa391fc"), "title" : "Book Title 2", "category" : "Fiction", "tags" : [ "teen", "fantasy" ], "user" : { "name" : "Ryan", "status" : "author" }, "date" : "Thu Aug 22 2019 12:59:50 GMT+0800 (PST)" }
{ "_id" : ObjectId("5d5e1c357545de885fa391fb"), "title" : "Book Title", "category" : "Fiction", "tags" : [ "children", "fantasy" ], "user" : { "name" : "Sophia", "status" : "author" }, "date" : "Thu Aug 22 2019 12:38:12 GMT+0800 (PST)" }