Databases Reference
In-Depth Information
"$where" queries should not be used unless strictly necessary: they are much slower
than regular queries. Each document has to be converted from BSON to a JavaScript
object and then run through the "$where" expression. Indexes cannot be used to satisfy
a "$where" , either. Hence, you should use "$where" only when there is no other way of
doing the query. You can cut down on the penalty by using other query filters in com-
bination with "$where" . If possible, an index will be used to filter based on the non-
$where clauses; the "$where" expression will be used only to fine-tune the results.
Another way of doing complex queries is to use MapReduce, which is covered in the
next chapter.
Cursors
The database returns results from find using a cursor . The client-side implementations
of cursors generally allow you to control a great deal about the eventual output of a
query. You can limit the number of results, skip over some number of results, sort
results by any combination of keys in any direction, and perform a number of other
powerful operations.
To create a cursor with the shell, put some documents into a collection, do a query on
them, and assign the results to a local variable (variables defined with "var" are local).
Here, we create a very simple collection and query it, storing the results in the cursor
variable:
> for(i=0; i<100; i++) {
... db.c.insert({x : i});
... }
> var cursor = db.collection.find();
The advantage of doing this is that you can look at one result at a time. If you store the
results in a global variable or no variable at all, the MongoDB shell will automatically
iterate through and display the first couple of documents. This is what we've been
seeing up until this point, and it is often the behavior you want for seeing what's in a
collection but not for doing actual programming with the shell.
To iterate through the results, you can use the next method on the cursor. You can use
hasNext to check whether there is another result. A typical loop through results looks
like the following:
> while (cursor.hasNext()) {
... obj = cursor.next();
... // do stuff
... }
cursor.hasNext() checks that the next result exists, and cursor.next() fetches it.
The cursor class also implements the iterator interface, so you can use it in a forEach
loop:
 
Search WWH ::




Custom Search