Databases Reference
In-Depth Information
Limitations
There are some restrictions on queries. The value of a query document must be a con-
stant as far as the database is concerned. (It can be a normal variable in your own code.)
That is, it cannot refer to the value of another key in the document. For example, if we
were keeping inventory and we had both "in_stock" and "num_sold" keys, we could
compare their values by querying the following:
> db.stock.find({"in_stock" : "this.num_sold"}) // doesn't work
There are ways to do this (see “$where Queries” on page 55 ), but you will usually get
better performance by restructuring your document slightly, such that a normal query
will suffice. In this example, we could instead use the keys "initial_stock" and
"in_stock" . Then, every time someone buys an item, we decrement the value of the
"in_stock" key by one. Finally, we can do a simple query to check which items are out
of stock:
> db.stock.find({"in_stock" : 0})
Query Criteria
Queries can go beyond the exact matching described in the previous section; they can
match more complex criteria, such as ranges, OR-clauses, and negation.
Query Conditionals
"$lt" , "$lte" , "$gt" , and "$gte" are all comparison operators, corresponding to <, <=,
>, and >=, respectively. They can be combined to look for a range of values. For ex-
ample, to look for users who are between the ages of 18 and 30 inclusive, we can do this:
> db.users.find({"age" : {"$gte" : 18, "$lte" : 30}})
These types of range queries are often useful for dates. For example, to find people who
registered before January 1, 2007, we can do this:
> start = new Date("01/01/2007")
> db.users.find({"registered" : {"$lt" : start}})
An exact match on a date is less useful, because dates are only stored with millisecond
precision. Often you want a whole day, week, or month, making a range query
necessary.
To query for documents where a key's value is not equal to a certain value, you must
use another conditional operator, "$ne" , which stands for “not equal.” If you want to
find all users who do not have the username “joe,” you can query for them using this:
> db.users.find({"username" : {"$ne" : "joe"}})
"$ne" can be used with any type.
 
Search WWH ::




Custom Search