Database Reference
In-Depth Information
db.products.find({main_cat_id: { $in:
[ObjectId("6a5b1476238d3b4dd5000048"),
ObjectId("6a5b1476238d3b4dd5000051"),
ObjectId("6a5b1476238d3b4dd5000057") ] } } )
Another way of thinking about the
$in
operator is as a kind of Boolean inclusive
OR
against a single attribute. Expressed this way, the previous query might be read, “Find
me all products whose category is lawnmowers or hand tools or work clothing.” Note
that if you need a Boolean
OR
over multiple attributes, you'll want to use the
$or
oper-
ator, described in the next section.
$in
is frequently used with lists of
ID
s. See the example earlier in this chapter for
an example of another query that uses
$in
to return all users who've bought a particu-
lar product.
$nin
returns a document only when none of the given elements matches. You
might use
$nin
to find all products that are neither black nor blue:
db.products.find('details.color': { $nin: ["black", "blue"] }
Finally,
$all
matches if every given element matches the search key. If you wanted to
find all products tagged as
gift
and
garden
,
$all
would be a good choice:
db.products.find(tags: { $all: ["gift", "garden"] }
Naturally, this query make sense only if the
tags
attribute stores an array of terms, like
this:
{ name: "Bird Feeder",
tags: [ "gift", "birds", "garden" ]
}
When using the set operators, keep in mind that
$in
and
$all
can take advantage of
indexes, but
$nin
can't and thus requires a collection scan. If you use
$nin
, try to use
it in combination with another query term that
does
use an index. Better yet, find a dif-
ferent way to express the query. You may, for instance, be able to store an attribute
whose presence indicates a condition equivalent to your
$nin
query. For example, if
you commonly issue a query for
{timeframe:
{$nin:
['morning',
'afternoon']}}
,
you may be able to express this more directly as
{timeframe:
'evening'}
.
B
OOLEAN
OPERATORS
MongoDB's Boolean operators include
$ne
,
$not
,
$or
,
$and
, and
$exists
.
$ne
, the
not equal to
operator, works as you'd expect. In practice, it's best used in
combination with at least one other operator; otherwise, it's likely to be inefficient
because it can't take advantage of indexes. For example, you might use
$ne
to find all
products manufactured by
ACME
that aren't tagged with
gardening
:
db.products.find('details.manufacturer': 'ACME', tags: {$ne: "gardening"} }
$ne
works on keys pointing to single values and to arrays, as shown in the example
where you match against the
tags
array.