MongoDB Sort Documents - sort() Method

In this post, we will learn how to sort records or documents in MongoDB using the sort() method.

The sort() Method

To sort documents in MongoDB, you need to use the sort() method. The method accepts a document containing a list of fields along with their sorting order. To specify sorting order 1 and -1 are used. 1 is used for ascending order while -1 is used for descending order.

Syntax

The basic syntax of the sort() method is as follows −
> db.COLLECTION_NAME.find().sort({KEY:1})

Example

Consider the collection "posts" has the following data.
> db.posts.find().pretty();
{
        "_id" : ObjectId("5e184a067695f4d696a0598d"),
        "title" : "MongoDB Overview",
        "description" : "MongoDB is no sql database",
        "by" : "Java Guides",
        "url" : "https://javaguides.net",
        "tags" : [
                "mongodb",
                "database",
                "NoSQL"
        ],
        "likes" : 100
}
{
        "_id" : ObjectId("5e184a067695f4d696a0598e"),
        "title" : "NoSQL Database",
        "description" : "NoSQL database doesn't have tables",
        "by" : "Java Guides",
        "url" : "https://javaguides.net",
        "tags" : [
                "mongodb",
                "database",
                "NoSQL"
        ],
        "likes" : 20,
        "comments" : [
                {
                        "user" : "user1",
                        "message" : "My first comment",
                        "dateCreated" : ISODate("2013-12-10T09:35:00Z"),
                        "like" : 0
                }
        ]
}
{
        "_id" : ObjectId("5e18544a7695f4d696a0598f"),
        "title" : "MongoDB CRUD Operations",
        "description" : "MongoDB CRUD Operations",
        "by" : "Java Guides",
        "url" : "https://javaguides.net",
        "tags" : [
                "mongodb",
                "database",
                "NoSQL"
        ],
        "likes" : 20,
        "comments" : [
                {
                        "user" : "user1",
                        "message" : "My first comment",
                        "dateCreated" : ISODate("2013-12-10T09:35:00Z"),
                        "like" : 0
                }
        ]
}
The following example will display the documents sorted by title in the descending order.
> db.posts.find({},{"title":1,_id:0}).sort({"title":-1});
{ "title" : "NoSQL Database" }
{ "title" : "MongoDB Overview" }
{ "title" : "MongoDB CRUD Operations" }

Default

The default is ascending order so If I don’t provide any value in the sort() method then it will sort the records in ascending order as shown below:
> db.posts.find({},{"title":1,_id:0}).sort({});
{ "title" : "MongoDB Overview" }
{ "title" : "NoSQL Database" }
{ "title" : "MongoDB CRUD Operations" }


Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours


Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course

Comments