Databases Reference
In-Depth Information
> var cursor = db.people.find();
> cursor.forEach(function(x) {
... print(x.name);
... });
adam
matt
zak
When you call find , the shell does not query the database immediately. It waits until
you actually start requesting results to send the query, which allows you to chain ad-
ditional options onto a query before it is performed. Almost every method on a cursor
object returns the cursor itself so that you can chain them in any order. For instance,
all of the following are equivalent:
> var cursor = db.foo.find().sort({"x" : 1}).limit(1).skip(10);
> var cursor = db.foo.find().limit(1).sort({"x" : 1}).skip(10);
> var cursor = db.foo.find().skip(10).limit(1).sort({"x" : 1});
At this point, the query has not been executed yet. All of these functions merely build
the query. Now, suppose we call the following:
> cursor.hasNext()
At this point, the query will be sent to the server. The shell fetches the first 100 results
or first 4MB of results (whichever is smaller) at once so that the next calls to next or
hasNext will not have to make trips to the server. After the client has run through the
first set of results, the shell will again contact the database and ask for more results.
This process continues until the cursor is exhausted and all results have been returned.
Limits, Skips, and Sorts
The most common query options are limiting the number of results returned, skipping
a number of results, and sorting. All of these options must be added before a query is
sent to the database.
To set a limit, chain the limit function onto your call to find . For example, to only
return three results, use this:
> db.c.find().limit(3)
If there are fewer than three documents matching your query in the collection, only the
number of matching documents will be returned; limit sets an upper limit, not a lower
limit.
skip works similarly to limit :
> db.c.find().skip(3)
This will skip the first three matching documents and return the rest of the matches. If
there are less than three documents in your collection, it will not return any documents.
sort takes an object: a set of key/value pairs where the keys are key names and the
values are the sort directions. Sort direction can be 1 (ascending) or -1 (descending). If
 
Search WWH ::




Custom Search