Agile metrics that matter LEARNOVITA

Sorting data in MongoDB ? : A Complete Guide For Beginners [ OverView ]

Last updated on 28th Jan 2023, Artciles, Blog

About author

Ranjan Binny (Senior Scrum Master and Agile Coach )

Ranjan Binny is a senior scrum master and agile coach with 7+ years of experience. He has extensive knowledge of Agile methodologies (Scrum, XP, Kanban), SDLC, database schema modeling, design patterns, SOAP, and REST web services, and experience in prioritizing, risk, and conflict management.

(5.0) | 19815 Ratings 2182
    • In this article you will learn:
    • 1.What is database sorting?
    • 2.MongoDB sort().
    • 3.Basic syntax of MongoDB sort().
    • 4.MongoDB sort() method usage.
    • 5.Conclusion.

What is database sorting?

Sorting data in a database puts it in an ascending or descending order based on the data in a certain field. Sorting operations can be done on different types of data such as:

  • Strings.
  • Integers.
  • Decimal.
  • Etc.

The main benefit of sorting is that it makes data easier to read and more uniform which makes it easier for users to understand what the data means.

MongoDB sort():

Sorting in MongoDB is done with a method called sort(). The sort() method is made up of just two main parts. These are the fields that need to be sorted and put in order.The order of things in a MongoDB is shown by a one (1) or a minus sign (-). (-1). Here a positive number means the order goes u and a negative number means the order goes down.

Basic syntax of MongoDB sort():

  • db.collection_name.find().sort({field_name: sort order})

According to official documentation MongoDB uses a following order when comparing values of various BSON types from lowest to highest. (BSON stands for a Binary JSON format.)This is a serialization format used in a MongoDB to store documents and make a remote procedure calls. Any non-existent fields in the document are treated as a Null objects.

1. MinKey (internal type)

2. Null

3. Numbers (ints, longs, doubles, decimals)

4. Symbol, String

5. Object

6. Array

7. BinData

8. ObjectId

9. Boolean

10. Date

11. Timestamp

12. Regular Expression

13. MaxKey (internal type)

MongoDB sort()

Unsorted collection:

When a find() method is used to do a search query the default behavior is to return an output that is not sorted. The _id:0 operator is used to get rid of the document ID to make the output simpler.

Sorted collection:

  • Add the sort() method to the end of the search query (find() method) to sort the results. This lets the user make an output that is in order.
  • In this case the “year” field is used to sort the data in an ascending order.
  • If you don’t give any arguments to a sort() method the collection won’t be sorted and the output will be in Mongo’s default order for finding results.

MongoDB sort() method usage:

This section will cover how a sort() method can be used to carry out a various sorting operations. Jump to a Sorting option you need:

  • In ascending order.
  • In descending order.
  • With multiple fields.
  • With the limit() method.
  • With the skip() method.
  • Metadata.
  • With an index.

Sorting in ascending order:

Use the “make” text field to obtain a results in ascending order. The operator one ({“make”:1}) is used to indicate a ascending order and MongoDB projection is used to filter out all other fields except a “make” field.

Sorting in descending order:

This example is a same as the above with a one difference which is using minus one ({“make”:-1}) operator to indicate a descending order.

Sorting using multiple fields:

  • If you want to sort more than one field you should declare the fields to be sorted inside the sort() method. The query will be sorted based on the position of the fields in the declaration with the sort order going from left to right. We’ll use the “vehicle sales” collection to show this.
  • The following example will show how to sort using a “make” and “price” fields. The data is a first sorted by “make” as it’s a first argument and then the data set will be further sorted by a “price” field.
  • db.vehiclesales.find({},{_id:0}).sort({“make”:1,”price”:1})
  • the data is first sorted by a make field. As there are multiple documents with a same make “Audi” the data gets sorted again by a price field in an ascending order resulting in above output.

Sorting with the limit() method:

  • The limit() method can be used with the sort() method to limit the number of search query results. should give an integer to the limit() method. This method will then tell the result set how many documents to show.
  • The following examples use a “vehicle information” collection with a limit of two documents and sorting in both ascending and descending order.
  • db.vehicle information.find({},{_id:0}).sort({“make”:1,”year”:1}).limit(2

Sorting with the skip() method:

Can also use a skip() method with the sort() method. The skip() method allows user to skip a specified number of the documents from the resulting dataset.In the following example you can see that the first four documents are skipped when they are put in ascending order by year.

  • db.vehicle information.find({},{_id:0}).sort({“year”:1}).skip(4).pretty
MongoDB sort() method

Metadata sorting:

The sort() method can be used to sort a metadata values for calculated a metadata field.The below example used a “food” collection to demonstrate how a documents can be sorted using a metadata textScore. The field name in the sort() method can be arbitrary as query system ignores a field name.“Food” collection:

  • db.food.find({},{_id:0}

Sorting with an index:

MongoDB can perform a sort operations on a single-field index in ascending or descending order. In a compound indexes the sort order finds whether the index can be sorted. The sort keys are must be listed in a same order as defined in an index.For example a compound index {make: 1, year: 1} can be sorted using sort({make: 1, year: 1}) but not on sort({year: 1, make: 1}). Sorting using an index helps to reduce a resource requirements when performing a query.

  • Using a “vehicle sales ” collection can explain an index named “make_index”.
  • db.vehiclesales.find({},{_id:0}).sort({make_index: 1}).
  • Here the index “make_index” is used to sort a documents. To identify which index is used can append the explain() method to end of the query which will result in a following output. From output can identify that the “make_index” is used to fetch a relevant documents.
  • db.vehiclesales.find({},{_id:0}).sort({make: 1}).explain().
  • Finally a query is run without an explain() method to obtain a output.

Conclusion:

Use a MongoDB sort() method in different scenarios including how to use it alongside the other methods to sort a given data set.Using a sort() method will increase readability of a query which leads to better understanding of a given dataset. Not only that sorted data will be used by a developers to write much complex algorithms.

Are you looking training with Right Jobs?

Contact Us

Popular Courses