Limiting Results by Size

The simplest way to limit the amount of data returned in a find() or another query request is to use the limit option in the options parameter when performing the request. The limit parameter, shown below, allows only a fixed number of items to be returned with the Cursor object. This can prevent you from accidentally retrieving more objects than your application can handle:

limit:<maximum_documents_to_return>

Listing 15.3 shows how to limit the results of a find() request by using the limit:5 option in the options object. The output in Figure 15.3 shows that when limit:5 is used, only five words are retrieved.

Listing 15.3 doc_limit.js: Limiting a specific 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", limitFind);
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 limitFind(err, words){
20   words.count({first:'p'}, function(err, count){
21     console.log("Count of words starting with p : " + count);
22   });
23   words.find({first:'p'}, function(err, cursor){
24     displayWords("Words starting with p : ", cursor);
25   });
26   words.find({first:'p'}, {limit:5}, function(err, cursor){
27     displayWords("Limiting words starting with p : ", cursor);
28   });
29 }


Image

Figure 15.3 Limiting the documents returned by a find() request.

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

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