Databases Reference
In-Depth Information
$not
"$not" is a metaconditional: it can be applied on top of any other criteria. As an example,
let's consider the modulus operator, "$mod" . "$mod" queries for keys whose values, when
divided by the first value given, have a remainder of the second value:
> db.users.find({"id_num" : {"$mod" : [5, 1]}})
The previous query returns users with "id_num" s of 1, 6, 11, 16, and so on. If we want,
instead, to return users with "id_num" s of 2, 3, 4, 5, 7, 8, 9, 10, 12, and so on, we can
use "$not" :
> db.users.find({"id_num" : {"$not" : {"$mod" : [5, 1]}}})
"$not" can be particularly useful in conjunction with regular expressions to find all
documents that don't match a given pattern (regular expression usage is described in
the section “Regular Expressions” on page 50 ).
Rules for Conditionals
If you look at the update modifiers in the previous chapter and previous query docu-
ments, you'll notice that the $-prefixed keys are in different positions. In the query,
"$lt" is in the inner document; in the update, "$inc" is the key for the outer document.
This generally holds true: conditionals are an inner document key, and modifiers are
always a key in the outer document.
Multiple conditions can be put on a single key. For example, to find all users between
the ages of 20 and 30, we can query for both "$gt" and "$lt" on the "age" key:
> db.users.find({"age" : {"$lt" : 30, "$gt" : 20}})
Any number of conditionals can be used with a single key. Multiple update modifiers
cannot be used on a single key, however. For example, you cannot have a modifier
document such as {"$inc" : {"age" : 1}, "$set" : {age : 40}} because it
modifies "age" twice. With query conditionals, no such rule applies.
Type-Specific Queries
As covered in Chapter 2 , MongoDB has a wide variety of types that can be used in a
document. Some of these behave specially in queries.
null
null behaves a bit strangely. It does match itself, so if we have a collection with the
following documents:
> db.c.find()
{ "_id" : ObjectId("4ba0f0dfd22aa494fd523621"), "y" : null }
 
Search WWH ::




Custom Search