Databases Reference
In-Depth Information
OR Queries
There are two ways to do an OR query in MongoDB. "$in" can be used to query for a
variety of values for a single key. "$or" is more general; it can be used to query for any
of the given values across multiple keys.
If you have more than one possible value to match for a single key, use an array of
criteria with "$in" . For instance, suppose we were running a raffle and the winning
ticket numbers were 725, 542, and 390. To find all three of these documents, we can
construct the following query:
> db.raffle.find({"ticket_no" : {"$in" : [725, 542, 390]}})
"$in" is very flexible and allows you to specify criteria of different types as well as values.
For example, if we are gradually migrating our schema to use usernames instead of user
ID numbers, we can query for either by using this:
> db.users.find({"user_id" : {"$in" : [12345, "joe"]})
This matches documents with a "user_id" equal to 12345, and documents with a
"user_id" equal to "joe" .
If "$in" is given an array with a single value, it behaves the same as directly matching
the value. For instance, {ticket_no : {$in : [725]}} matches the same documents as
{ticket_no : 725} .
The opposite of "$in" is "$nin" , which returns documents that don't match any of the
criteria in the array. If we want to return all of the people who didn't win anything in
the raffle, we can query for them with this:
> db.raffle.find({"ticket_no" : {"$nin" : [725, 542, 390]}})
This query returns everyone who did not have tickets with those numbers.
"$in" gives you an OR query for a single key, but what if we need to find documents
where "ticket_no" is 725 or "winner" is true ? For this type of query, we'll need to use
the "$or" conditional. "$or" takes an array of possible criteria. In the raffle case, using
"$or" would look like this:
> db.raffle.find({"$or" : [{"ticket_no" : 725}, {"winner" : true}]})
"$or" can contain other conditionals. If, for example, we want to match any of the three
"ticket_no" values or the "winner" key, we can use this:
> db.raffle.find({"$or" : [{"ticket_no" : {"$in" : [725, 542, 390]}},
{"winner" : true}]})
With a normal AND-type query, you want to narrow your results down as far as pos-
sible in as few arguments as possible. OR-type queries are the opposite: they are most
efficient if the first arguments match as many documents as possible.
 
Search WWH ::




Custom Search