Another extremely effective method of limiting the resulting data when retrieving documents is to limit which fields are returned. Documents may have a lot of different fields that are useful in some circumstance but not in others. You should consider which fields should be included when retrieving documents from the MongoDB server and only request the ones that are necessary.
To limit the fields returned from a server, use the fields
option of the options
object. The fields
option in an object allows you to either include or exclude fields by setting the value of the document
field to 0
for exclude or 1
for include. You cannot mix inclusions and exclusions in the same expression.
For example, to exclude the fields stats
, value
, and comments
when returning a document, you use the following fields
option:
{fields:{stats:0, value:0, comments:0}}
Often it is easier to just include a few fields. For example, if you want to include only the name
and value
fields of documents, you use:
{fields:{name:1, value:1}}
Listing 15.4 shows how to use the fields
option to reduce the amount of data returned from the server by excluding fields or specifying specific fields to include. Figure 15.4 shows the output of Listing 15.4.
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", limitFields);
05 setTimeout(function(){
06 db.close();
07 }, 3000);
08 });
09 function limitFields(err, words){
10 words.findOne({word:'the'}, {fields:{charsets:0}},
11 function(err, item){
12 console.log("Excluding fields object: ");
13 console.log(JSON.stringify(item, null, 2));
14 });
15 words.findOne({word:'the'}, {fields:{word:1,size:1,stats:1}},
16 function(err, item){
17 console.log("Including fields object: ");
18 console.log(JSON.stringify(item, null, 2));
19 });
20 }