MongoDBJavascriptTypescript
Last updated at 2023-09-07

Sort() Method to Order Query Results in MongoDB

ClickUp
Last Edit By
Last edited time
Sep 7, 2023 01:13 PM
Metatag
Slug
sort-order-query-mongodb
AI Status
FULL
Published
Published
Date
Sep 7, 2023
Category
MongoDB
Javascript
Typescript
MongoDB, a NoSQL database, doesn't inherently guarantee any specific order for query results.
However, you can specify how you want to sort the documents in your query result using the sort() method in MongoDB.
In this tutorial, you will learn how to sort query result using sort() method in MongoDB.

Sample Code

To demonstrate how to use sorting in MongoDB, let's first create a sample collection and insert four documents into it.
Then, we'll show you a complete MongoDB query that utilizes the sort() method to sort the results.
We'll also discuss different sorting methods and provide examples of single and multiple field sorting.

Creating a Sample Collection and Inserting Documents

// Create a sample collection named 'posts' db.createCollection("posts") // Insert sample documents db.posts.insertMany([ { title: "Post 1", categories: ["Tech", "Programming"], lastEditedAt: ISODate("2023-01-15T10:30:00Z"), cover: null }, { title: "Post 2", categories: ["Science", "Space"], lastEditedAt: ISODate("2023-02-20T14:45:00Z"), cover: "science" }, { title: "Post 3", categories: ["Food"], lastEditedAt: ISODate("2023-03-10T08:15:00Z"), cover: "food" }, { title: "Post 4", categories: ["Tech", "Gaming"], lastEditedAt: ISODate("2023-04-05T16:00:00Z"), cover: "tech" } ])
In the MongoDB code above, we've created a collection named 'posts' and inserted four sample documents.

Complete Query with Sorting

The following MongoDB query demonstrates how to use the sort() method to sort the query results:
db.posts.find({}, { title: 1, categories: 1, lastEditedAt: 1, cover: 1 }).sort({ title: 1, categories_count: -1, cover: 1 })
In this query, we select specific fields from the 'posts' collection and sort the results based on three criteria: 'title' in ascending order, 'categories_count' in descending order (this is a custom field based on array length), and 'cover' in ascending order.

Available Sort Methods in MongoDB

In MongoDB, you can specify sorting methods for each field you want to sort by using the sort() method.
Here are the available sorting methods:
  • 1: Ascending order (similar to ASC in SQL).
  • -1: Descending order (similar to DESC in SQL).

Single Field Sorting

You can perform single field sorting in MongoDB by specifying the field and the desired sorting method in the sort() method.

Example:

db.posts.find({}, { title: 1 }).sort({ title: 1 })
In this query, we select only the 'title' field and sort the results by 'title' in ascending order.

Multiple Field Sorting

You can also sort by multiple fields in MongoDB by including multiple fields and sorting methods in the sort() method.

Example:

db.posts.find({}, { title: 1 }).sort({ title: 1, categories_count: -1 })
In this query, we first sort the results by 'title' in ascending order and then by 'categories_count' in descending order, creating a hierarchical sorting.

Conclusion

Sorting in MongoDB is accomplished using the sort() method, which allows you to specify the sorting methods for each field you want to sort by.
This flexibility enables you to present your data in a structured and meaningful way, making it easier for users to interpret the results.
Happy Sorting in MongoDB!

Discussion (0)

Related Posts