A very useful query against a MongoDB collection is to get a list of the distinct values for a single field in a set of documents. Distinct in this case means that even though there are thousands of documents, you only want to know the unique values that exist.
The distinct()
method on Collection
objects allows you to find a list of distinct values for a specific field. The syntax for the distinct()
method is shown below:
distinct(key,[query],[options],callback)
The key
parameter is the string value of the fieldname you want to get values for. You can specify subdocuments by using the dot syntax—for example, stats.count
. The query
parameter is an object with the standard query
object options listed in Table 15.1. The options
parameter is an options
object that allows you to define the readPreference
option defined in Table 15.2. The callback function accepts an error as the first parameter and then a results
parameter, which is an array of distinct values for the field specified in the key
parameter.
Listing 15.7 shows how to find the distinct values in the words collection. Notice that the query in line 14 limits the words to those starting with u
. Notice that line 18 uses dot syntax to access the stats.vowels
field. Figure 15.7 shows the output of Listing 15.7.
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", distinctValues);
05 setTimeout(function(){
06 db.close();
07 }, 3000);
08 });
09 function distinctValues(err, words){
10 words.distinct('size', function(err, values){
11 console.log("
Sizes of words: ");
12 console.log(values);
13 });
14 words.distinct('first', {last:'u'}, function(err, values){
15 console.log("
First letters of words ending in u: ");
16 console.log(values);
17 });
18 words.distinct('stats.vowels', function(err, values){
19 console.log("
Numbers of vowels in words: ");
20 console.log(values);
21 });
22 }