MongoDB

MongoDB Sort Function

In this tutorial, we will explore how to use the MongoDB sort function. This function allows us to define the order in which the MongoDB cursor returns matching documents.

The function syntax is as shown:

db.Collection.sort({field: value < 1 | -1>})

The function accepts the document containing a specific field and the sorting order. The value of 1 shows an ascending order while -1 indicates a descending sort order.

The function will return the queried documents sorted in the specified order as defined in the field and value parameters.

Example

Start by creating a collection and adding some sample documents.

The query is as shown:

db.createCollection("films")
db.films.insertMany(
    [
        {
"show_id": "s1",
"type": "Movie",
"title": "Dick Johnson Is Dead",
"director": "Kirsten Johnson",
"cast": null,
"country": "United States",
"date_added": "September 25, 2021",
"release_year": NumberInt(2020),
"rating": "PG-13",
"duration": "90 min",
"listed_in": "Documentaries"
        },
        {
"show_id": "s2",
"type": "TV Show",
"title": "Blood & Water",
"director": null,
"cast": null,
"country": "South Africa",
"date_added": "September 24, 2021",
"release_year": NumberInt(2021),
"rating": "TV-MA",
"duration": "2 Seasons",
"listed_in": "International TV Shows, TV Dramas, TV Mysteries",
        },
        {
"show_id": "s3",
"type": "TV Show",
"title": "Ganglands",
"director": "Julien Leclercq",
"cast": null,
"country": null,
"date_added": "September 24, 2021",
"release_year": NumberInt(2021),
"rating": "TV-MA",
"duration": "1 Season",
"listed_in": "Crime TV Shows, International TV Shows, TV Action & Adventure",
        },
        {
"show_id": "s4",
"type": "TV Show",
"title": "Jailbirds New Orleans",
"director": null,
"cast": null,
"country": null,
"date_added": "September 24, 2021",
"release_year": NumberInt(2021),
"rating": "TV-MA",
"duration": "1 Season",
"listed_in": "Docuseries, Reality TV",
        },
        {
"show_id": "s5",
"type": "TV Show",
"title": "Kota Factory",
"director": null,
"cast": null,
"country": "India",
"date_added": "September 24, 2021",
"release_year": NumberInt(2021),
"rating": "TV-MA",
"duration": "2 Seasons",
"listed_in": "International TV Shows, Romantic TV Shows, TV Comedies",
        }
    ]
)

From the documents above, we can use the sort function to sort the documents based on the rating in ascending order.

The query is as shown:

db.films.find().sort({"rating": 1})

Running the query above will sort the documents in alphabetical order based on the rating field. It is good to keep in mind that since the collection contains duplicate values for the ratings, the sort order may be inconsistent across several executions.

We can also sort the documents in descending order by setting the sort value to -1. An example is as shown:

db.films.find().sort({"release_year": -1})

The query above should return the documents sorted in descending order based on the release_year field.

The resulting output is as shown:

{
    "_id" : ObjectId("632af6b69c8d85d13eb419a4"),
    "show_id" : "s2",
    "type" : "TV Show",
    "title" : "Blood & Water",
    "director" : null,
    "cast" : null,
    "country" : "South Africa",
    "date_added" : "September 24, 2021",
    "release_year" : NumberInt(2021),
    "rating" : "TV-MA",
    "duration" : "2 Seasons",
    "listed_in" : "International TV Shows, TV Dramas, TV Mysteries"
}
{
    "_id" : ObjectId("632af6b69c8d85d13eb419a5"),
    "show_id" : "s3",
    "type" : "TV Show",
    "title" : "Ganglands",
    "director" : "Julien Leclercq",
    "cast" : null,
    "country" : null,
    "date_added" : "September 24, 2021",
    "release_year" : NumberInt(2021),
    "rating" : "TV-MA",
    "duration" : "1 Season",
    "listed_in" : "Crime TV Shows, International TV Shows, TV Action & Adventure"
}
{
    "_id" : ObjectId("632af6b69c8d85d13eb419a6"),
    "show_id" : "s4",
    "type" : "TV Show",
    "title" : "Jailbirds New Orleans",
    "director" : null,
    "cast" : null,
    "country" : null,
    "date_added" : "September 24, 2021",
    "release_year" : NumberInt(2021),
    "rating" : "TV-MA",
    "duration" : "1 Season",
    "listed_in" : "Docuseries, Reality TV"
}
{
    "_id" : ObjectId("632af6b69c8d85d13eb419a7"),
    "show_id" : "s5",
    "type" : "TV Show",
    "title" : "Kota Factory",
    "director" : null,
    "cast" : null,
    "country" : "India",
    "date_added" : "September 24, 2021",
    "release_year" : NumberInt(2021),
    "rating" : "TV-MA",
    "duration" : "2 Seasons",
    "listed_in" : "International TV Shows, Romantic TV Shows, TV Comedies"
}
{
    "_id" : ObjectId("632af6b69c8d85d13eb419a3"),
    "show_id" : "s1",
    "type" : "Movie",
    "title" : "Dick Johnson Is Dead",
    "director" : "Kirsten Johnson",
    "cast" : null,
    "country" : "United States",
    "date_added" : "September 25, 2021",
    "release_year" : NumberInt(2020),
    "rating" : "PG-13",
    "duration" : "90 min",
    "listed_in" : "Documentaries"
}

Conclusion

In this article, we discussed how to use the cursor.sort() method in MongoDB. We can use the sort() function to sort the results of a query in ascending or descending order.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list