Sorting Result Sets

An important aspect of retrieving documents from a MongoDB database is the ability to get it in a sorted format. Sorting is especially helpful if you are only retrieving a certain number, such as the top 10, or if you are paging the requests. The options object provides the sort option, which allows you to specify the sort order and direction of one or more fields in a document.

You specify the sort option by using an array of [field,<sort_order>] pairs, where sort_order is 1 for ascending and -1 for descending. For example, to sort on the name field descending first and then on the value field ascending, you would use:

sort:[['name':1]['value':-1]]

Listing 15.6 shows how to use the sort option to find and sort lists of words in different ways. Notice that line 29 sorts the words by size first and then by last letter, whereas line 32 sorts them by last letter first and then by size. The different sort orders return different lists of words. Figure 15.6 shows the output from the code in Listing 15.6.

Listing 15.6 doc_sort.js: Sorting results of a find() request for a set of documents in a MongoDB collection


01 var MongoClient = require('mongodb').MongoClient;
02 MongoClient.connect("mongodb://localhost/", function(err, db) {
03   var myDB = db.db("words");
04   myDB.collection("word_stats", sortItems);
05   setTimeout(function(){
06     db.close();
07   }, 3000);
08 });
09 function displayWords(msg, cursor, pretty){
10   cursor.toArray(function(err, itemArr){
11     console.log(" "+msg);
12     var wordList = [];
13     for(var i=0; i<itemArr.length; i++){
14       wordList.push(itemArr[i].word);
15     }
16     console.log(JSON.stringify(wordList, null, pretty));
17   });
18 }
19 function sortItems(err, words){
20   words.find({last:'w'}, function(err, cursor){
21     displayWords("Words ending in w: ", cursor);
22   });
23   words.find({last:'w'}, {sort:{word:1}}, function(err, cursor){
24     displayWords("Words ending in w sorted ascending: ", cursor);
25   });
26   words.find({last:'w'}, {sort:{word:-1}}, function(err, cursor){
27     displayWords("Words ending in w sorted, descending: ", cursor);
28   });
29   words.find({first:'b'}, {sort:[['size',-1],['last',1]]},
30              function(err, cursor){
31     displayWords("B words sorted by size then by last letter: ", cursor);
32   });
33   words.find({first:'b'}, {sort:[['last',1],['size',-1]]},
34              function(err, cursor){
35     displayWords("B words sorted by last letter then by size: ", cursor);
36   });
37 }


Image

Figure 15.6 Sorting the results of a find() request for specific documents in a MongoDB collection.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.161.251