Finding Specific Sets of Documents

In Chapter 14, “Manipulating MongoDB Documents from Node.js,” you learned about the find() method of the Collection object. This method returns a Cursor object to the callback function, providing access to the documents. If no query is specified, then all documents are returned, which is rarely what you want. Instead, you typically need a subset of documents that match a certain set of criteria.

To limit the number of documents the find() method finds, you apply a query object that limits the documents that will be returned in the Cursor object.

The code in Listing 15.1 performs a bunch of different queries against the word collection data set described earlier in this chapter. You should already recognize all the connection code as well as the code used in displayWords() to iterate through the cursor and display only the word names in the documents.

In line 20 the following query looks for words that start with a, b, or c:

{first:{$in: ['a', 'b', 'c']}}

In line 23 the following query looks for words longer than 12 letters:

{size:{$gt: 12}}

In line 26 the following query looks for words with an even number of letters:

{size:{$mod: [2,0]}}

In line 29 the following query looks for words with exactly 12 letters:

{letters:{$size: 12}}

In lines 32 and 33 the following query looks for words that both begin and end with a vowel:

{$and: [{first:{$in: ['a', 'e', 'i', 'o', 'u']}},
        {last:{$in: ['a', 'e', 'i', 'o', 'u']}}]}

In line 37 the following query looks for words that contain more than six vowels:

{"stats.vowels":{$gt:6}}

In line 40 the following query looks for words that contain all of the vowels:

{letters:{$all: ['a','e','i','o','u']}}

In line 44 the following query looks for words with non-alphabet characters:

{otherChars: {$exists:true}}

Line 47 uses a query that’s rather challenging. It uses the $elemMatch operator to match the charsets subdocuments. The $and operator forces the type field to equal other and the chars array field to be exactly 2:

{charsets:{$elemMatch:{$and:[{type:'other'},{chars:{$size:2}}]}}}

Figure 15.1 shows the output from Listing 15.1.

Listing 15.1 doc_query.js: Finding 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", findItems);
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 findItems(err, words){
20   words.find({first:{$in: ['a', 'b', 'c']}}, function(err, cursor){
21     displayWords("Words starting with a, b or c: ", cursor);
22   });
23   words.find({size:{$gt: 12}}, function(err, cursor){
24     displayWords("Words longer than 12 characters: ", cursor);
25   });
26   words.find({size:{$mod: [2,0]}}, function(err, cursor){
27     displayWords("Words with even Lengths: ", cursor);
28   });
29   words.find({letters:{$size: 12}}, function(err, cursor){
30     displayWords("Words with 12 Distinct characters: ", cursor);
31   });
32   words.find({$and: [{first:{$in: ['a', 'e', 'i', 'o', 'u']}},
33                      {last:{$in: ['a', 'e', 'i', 'o', 'u']}}]},
34              function(err, cursor){
35     displayWords("Words that start and end with a vowel: ", cursor);
36   });
37   words.find({"stats.vowels":{$gt:6}}, function(err, cursor){
38     displayWords("Words containing 7 or more vowels: ", cursor);
39   });
40   words.find({letters:{$all: ['a','e','i','o','u']}},
41              function(err, cursor){
42     displayWords("Words with all 5 vowels: ", cursor);
43   });
44   words.find({otherChars: {$exists:true}}, function(err, cursor){
45     displayWords("Words with non-alphabet characters: ", cursor);
46   });
47   words.find({charsets:{$elemMatch:{$and:[{type:'other'},
48                                           {chars:{$size:2}}]}}},
49              function(err, cursor){
50     displayWords("Words with 2 non-alphabet characters: ", cursor);
51   });
52 }


Image

Figure 15.1 Finding specific documents in MongoDB by using query objects in find().

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

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