Database Reference
In-Depth Information
The
count()
command shows that you've inserted 200,000 documents. The subse-
quent query displays the first 20 results. You can display additional results with the
it
command:
> it
{ "_id" : ObjectId("4bfbf132dba1aa7c30ac831e"), "num" : 20 }
{ "_id" : ObjectId("4bfbf132dba1aa7c30ac831f"), "num" : 21 }
{ "_id" : ObjectId("4bfbf132dba1aa7c30ac8320"), "num" : 22 }
...
The
it
command instructs the shell to return the next result set.
1
With a sizeable set of documents available, let's try a few queries. Given what you
know about MongoDB's query engine, a simple query matching a document on its
num
attribute makes sense:
> db.numbers.find({num: 500})
{ "_id" : ObjectId("4bfbf132dba1aa7c30ac84fe"), "num" : 500 }
But more interestingly, you can also issue range queries using the special
$gt
and
$lt
operators. You first saw these operators in chapter 1. (They stand for
greater than
and
less than
, respectively.) Here's how you query for all documents with a
num
value
greater than 199,995:
> db.numbers.find( {num: {"$gt": 199995 }} )
{ "_id" : ObjectId("4bfbf1dedba1aa7c30afcade"), "num" : 199996 }
{ "_id" : ObjectId("4bfbf1dedba1aa7c30afcadf"), "num" : 199997 }
{ "_id" : ObjectId("4bfbf1dedba1aa7c30afcae0"), "num" : 199998 }
{ "_id" : ObjectId("4bfbf1dedba1aa7c30afcae1"), "num" : 199999 }
You can also combine the two operators to specify upper and lower boundaries:
> db.numbers.find( {num: {"$gt": 20, "$lt": 25 }} )
{ "_id" : ObjectId("4bfbf132dba1aa7c30ac831f"), "num" : 21 }
{ "_id" : ObjectId("4bfbf132dba1aa7c30ac8320"), "num" : 22 }
{ "_id" : ObjectId("4bfbf132dba1aa7c30ac8321"), "num" : 23 }
{ "_id" : ObjectId("4bfbf132dba1aa7c30ac8322"), "num" : 24 }
You can see that by using a simple
JSON
document, you're able to specify a sophisti-
cated range query much in the way you might do in
SQL
. Because
$gt
and
$lt
are just
two of a host of special keywords that comprise the MongoDB query language, you'll
be seeing many more example queries in later chapters.
Of course, queries like this are of little value if they're not also efficient. In the next
section, we'll start thinking about query efficiency by exploring MongoDB's indexing
features.
1
You may be wondering what's happening behind the scenes here. All queries create a cursor, which allows for
iteration over a result set. This is somewhat hidden when using the shell, so it's not necessary to discuss in
detail at the moment. If you can't wait to learn more about cursors and their idiosyncrasies, see chapters 3
and 4.