Cara menggunakan find sort mongodb

Pada SQL terdapat cara untuk melakukan pengurutan dan pembatasan jumlah data yang akan di ambil, begitu juga pada mongodb. This is the way in PHP :

            
            $connection = new Mongo(); // make a definition mongodb
            $database = $connection->selectDB('belajar');  // get a database from mongodb
            $collection = $database->selectCollection('siswa');  // get a collection
            $result= $collection->find(); // query like "SELECT * FROM siswa"
            $result->sort(array('jk'=>1,'kota'=>-1));  // make a sort with field "jk" and "kota"
            $result->limit(2); // make a limit data that we want to get

Dapat anda lihat pada fungsi sort, terdapat beberapa data dalam bentuk array. Karena array, kita dapat mengurutkan datanya dari lebih dari 1 field. Kemudian dapat dilihat “jk”=>1 maksudnya adalah akan diurutkan dengan document “jk” dan ascending. Sedangkan jika dituliskan “-1” maka artinya diurutkan dengan descending. Anda dapat menentukan document yang digunakan untuk pengurutan dan menentukan juga ascending atau descendingnya..

Actually I got some trick to do that, lets create the function first with name handleQuerySort(), you can create the function anywhere. but it’s good to put in your helper.

First I’ll convert the query string to look like json object using javascript methods like replace() and substring().

Then I’ll parse the string to object using JSON.parse() function.

Then I’ll wrap the codes with try and catch to prevent wrong query format from clients.

Last, lets use the function in mongoose sort.

Testing Results:

*default result

Cara menggunakan find sort mongodb

Unsorted collection

When a search query is carried out with the find() method, the default behavior is to return the output unsorted. The {_id:0} operator is used to remove the document ID for a simpler output.

db.vehicleinformation.find({},{_id:0})

Results in:

Cara menggunakan find sort mongodb

Sorted collection

To get a sorted result, we append the sort() method to the end of the search query (find() method). This allows the user to generate a sorted output.

In this instance, the data is sorted by the “year” field in ascending order.

db.vehicleinformation.find({},{_id:0}).sort({"year":1})

Results in:

Cara menggunakan find sort mongodb

If you don’t give any arguments to the sort() method, the collection will not be sorted, and the resulting output will be in the default order—which is the order Mongo finds the results.

db.vehicleinformation.find({},{_id:0}).sort({})<.pre>

Result:

Cara menggunakan find sort mongodb

MongoDB sort() method usage

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

Sorting in ascending order

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

db.vehicleinformation.find({},{make:1,_id:0}).sort({"make":1})

Result:

Cara menggunakan find sort mongodb

Sorting in descending order

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

db.vehicleinformation.find({},{make:1,_id:0}).sort({"make":-1})

Result:

Cara menggunakan find sort mongodb

Sorting using multiple fields

When sorting multiple fields, you should declare fields to be sorted within the sort() method. The query will be sorted according to the declaration position of the fields, where the sort order is evaluated from left to right. To demonstrate this, we will be using “vehiclesales” collection.

“vehiclessales” collection

db.vehiclesales.find({},{_id:0})

Result:

Cara menggunakan find sort mongodb

The following example will show how to sort using the “make” and “price” fields. The data is first sorted by “make” as it’s the first argument, and then the data set will be further sorted by the “price” field.

db.vehiclesales.find({},{_id:0}).sort({"make":1,"price":1})

Result:

Cara menggunakan find sort mongodb

As shown above, the data is first sorted by the make field. As there are multiple documents with the same make “Audi,” the data gets sorted again by the price field in an ascending order resulting in the above output.

Sorting with the limit() method

The sort() method can be used along with the limit() method that limits the number of results in the search query. You should pass an integer to the limit() method, which then specifies the number of documents to which the result set should be limited.

The following examples use the “vehicleinformation” collection while the result is limited to two documents and sorted by both the ascending and descending order.

db.vehicleinformation.find({},{_id:0}).sort({"make":1,"year":1}).limit(2).pretty()

Result:

Cara menggunakan find sort mongodb

db.vehicleinformation.find({},{_id:0}).sort({"make":-1,"year":-1}).limit(2).pretty()

Results in:

Cara menggunakan find sort mongodb

Sorting with the skip() method

You can also use the skip() method with the sort() method. The skip() method allows the user to skip a specified number of documents from the resulting dataset.

In the following example, You can see the first four documents are being skipped while being sorted by the year in ascending order.

db.vehicleinformation.find({},{_id:0})
0

Result:

Cara menggunakan find sort mongodb

Metadata sorting

The sort() method can be used to sort the metadata values for a calculated metadata field.

The following example used the “food” collection to demonstrate how documents can be sorted using the metadata “textScore.” The field name in the sort() method can be arbitrary as the query system ignores the field name.

“Food” collection

db.vehicleinformation.find({},{_id:0})
1

Result:

Cara menggunakan find sort mongodb

db.vehicleinformation.find({},{_id:0})
2

Result:

Cara menggunakan find sort mongodb

In this query, we have specified the sort field as “sort_example.” However, this is ignored as we are sorting metadata. Moreover, since we are sorting using “textScore” metadata, the resulting data set is sorted in descending order.

Sorting with an index

MongoDB can perform sort operations on a single-field index in ascending or descending order. In compound indexes, the sort order determines whether the index can be sorted. The sort keys must be listed in the same order as defined in the index.

For example, the 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 the resource requirements when performing the query.

Using the “vehicleslaes ” collection, we define an index named “make_index”

db.vehicleinformation.find({},{_id:0})
3

Result:

Cara menggunakan find sort mongodb

Here, the index “make_index” is used to sort the documents. To identify which index is used, we append the explain() method to the end of the query, which will result in the following output. From the output, we can identify that the “make_index” is used to fetch the relevant documents.

db.vehicleinformation.find({},{_id:0})
4

Result:

Cara menggunakan find sort mongodb

Finally, the query is run without the explain() method to obtain the output.

db.vehicleinformation.find({},{_id:0})
5

Result:

Cara menggunakan find sort mongodb

That’s the end of our MongoDB sorting tutorial. Explore the right-hand menu for more MongoDB concepts and examples.