Database Reference
In-Depth Information
transform the query results into a simple array of ID s and then use that array to query
the users collection with the $in operator:
user_ids = db.orders.find({'line_items.sku': "9092",
purchase_date: {'$gt': new Date(2009, 0, 1)}},
{user_id: 1, _id: 0}).toArray().map(function(doc) { return doc['_id'] })
users = db.users.find({_id: {$in: user_ids}})
This technique of querying a collection using an array of ID s and $in will be efficient
for arrays of ID s having up to a few thousand elements. For larger data sets, where you
might have a million users who've purchased the wheelbarrow, it'll be more prudent to
write those user ID s to a temporary collection and then process the query sequentially.
You'll see more examples of querying this data in the next chapter, and later on,
you'll learn how to get insight from the data using MongoDB's aggregation functions.
But with this introduction under your belt, we're now going to look at MongoDB's
query language in some depth, explaining the syntax in general and each operator in
particular.
5.2
MongoDB's query language
It's time we explore MongoDB's query language in all its glory. I'll begin with a gen-
eral description of queries, their semantics, and their types. I'll then discuss cursors,
since every MongoDB query is, fundamentally, the instantiation of a cursor and the
fetching of that cursor's result set. With these fundamentals out of the way, I'll present
a taxonomy of all MongoDB query operators. 4
5.2.1
Query selectors
We begin with an overview of query selectors, paying particular attention to all the
kinds of queries you can express with them.
S ELECTOR MATCHING
The simplest way to specify a query is with a selector whose key-value pairs literally
match against the document you're looking for. A couple of examples:
db.users.find({last_name: "Banker"})
db.users.find({first_name: "Smith", age: 40})
The second query reads, “Find me all users such that the first_name is Smith and the
age is 40.” Note that whenever you pass more than one key-value pair, both must
match; the query conditions function as a Boolean AND . If you want to express a Bool-
ean OR, see the upcoming section on Boolean operators.
R ANGES
You frequently need to query for documents whose values span a certain range. In
SQL , you use < , <= , > , and >= ; with MongoDB, you get the analogous set of operators
$lt , $lte , $gt , and $gte . You've been using these operators throughout the topic,
4
Unless you're a glutton for details, this taxonomy may safely be skimmed on first reading.
Search WWH ::




Custom Search