One of the tasks that you commonly need to perform on data stored in a MongoDB database is retrieving one or more documents. For example, consider product information for products on a commercial website. The information is stored once but retrieved many times.
The retrieval of data sounds fairly simple, but it can become quite complex as you need to also filter, sort, limit, and aggregate the results. In fact, Chapter 15, “Accessing MongoDB Documents from Node.js,” is devoted to the complexities of retrieving data.
This section introduces you to the simple basics of the find()
and findOne()
methods of the Collection
object to make it easier to understand the code examples in this chapter. The syntax for the find()
and findOne()
methods is shown below:
find(query, [options], callback)
findOne(query, [options], callback)
Both find()
and findOne()
accept a query
object as the first parameter. The query
object contains properties that are matched against fields in the documents. Documents that match the query
object are included in the list. The options
parameter is an object that specifies everything else about the search for documents, such as the limit, sort, and what to return.
The callback function is where find()
and findOne()
differ. The find()
method returns a Cursor
object that can be iterated on to retrieve documents. On the other hand, the findOne()
method returns a single object.
Listing 14.2 illustrates how to use find()
and findOne()
. Lines 5–10 implement find()
. Notice that the result is a Cursor
object. To display the results, the toArray()
method iterates through the Cursor
object and builds a basic JavaScript array of objects. This allows you to operate on the documents as you would a normal set of JavaScript objects.
Lines 11–18 use the find()
method and also the each()
method to iterate through the Cursor
object. The each()
method iterates through the documents represented in the Cursor
object one at a time. For each iteration, a single document is retrieved from MongoDB and passed in as the second parameter to the callback
function.
Lines 19–22 implement the findOne()
method. Notice the simple query on the type
field. The callback function receives the object and outputs it to the screen, as shown in Figure 14.2.
01 var MongoClient = require('mongodb').MongoClient;
02 MongoClient.connect("mongodb://localhost/", function(err, db) {
03 var myDB = db.db("astro");
04 myDB.collection("nebulae", function(err, nebulae){
05 nebulae.find(function(err, items){
06 items.toArray(function(err, itemArr){
07 console.log("Document Array: ");
08 console.log(itemArr);
09 });
10 });
11 nebulae.find(function(err, items){
12 items.each(function(err, item){
13 if(item){
14 console.log("Singular Document: ");
15 console.log(item);
16 }
17 });
18 });
19 nebulae.findOne({type:'planetary'}, function(err, item){
20 console.log("Found One: ");
21 console.log(item);
22 });
23 });
24 setTimeout(function(){ db.close(); }, 3000);
25 });