Aggregation Examples

Listing 15.9 shows how to implement aggregation against the words collection. It includes three examples.

The first example, in lines 10–20, implements a $match to get words beginning in vowels, then a $group to calculate the largest and smallest sizes. It then sorts the results using $sort, as shown in Figure 15.9.

Image

Figure 15.9 Grouping documents from a MongoDB collection by specific field values.

The second example, in lines 21–27, uses $match to limit the words to four letters. Then $limit is used to process only five documents in the $project operator.

The third example, in lines 28–34, uses $group to get the average size of the words and sets the _id value of each to that word. Then it sorts the words in descending order by average, as shown in Figure 15.9.

Listing 15.9 doc_aggregate.js: Grouping a set of documents by specific fields 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", aggregateItems);
05   setTimeout(function(){
06     db.close();
07   }, 3000);
08 });
09 function aggregateItems(err, words){
10   words.aggregate([{$match: {first:{$in:['a','e','i','o','u']}}},
11                    {$group: {_id:"$first",
12                              largest:{$max:"$size"},
13                              smallest:{$min:"$size"},
14                              total:{$sum:1}}},
15                    {$sort: {_id:1}}],
16               function(err, results){
17     console.log("Largest and smallest word sizes for " +
18                 "words beginning with a vowel: ");
19     console.log(results);
20   });
21   words.aggregate([{$match: {size:4}},
22                    {$limit: 5},
23                    {$project: {_id:"$word", stats:1}}],
24               function(err, results){
25     console.log("Stats for 5 four letter words: ");
26     console.log(results);
27   });
28   words.aggregate([{$group: {_id:"$first", average:{$avg:"$size"}}},
29                     {$sort: {average:-1}},
30                     {$limit: 5}],
31               function(err, results){
32     console.log("Letters with largest average word size: ");
33     console.log(results);
34   });
35 }


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

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