Database Reference
In-Depth Information
Siblings are any other categories with the same parent ID , so the query for siblings is
straightforward. Since products all contain an array of category ID s, the query to find
all products in a given category is also trivial. You also apply the same pagination pat-
tern that you used for reviews, except that you sort by average product rating. You can
imagine providing alternative sort methods (by name, price, and so forth). For those
cases, you simply change the sort field. 1
The product listing page has a base case, where you're viewing just the root-level
categories but no products. A query against the categories collection for a nil parent
ID is all that's required to get these root-level categories:
categories = db.categories.find({'parent_id': nil})
5.1.2
Users and orders
The queries in the previous section were generally limited to _id lookups and sorts. In
looking at users and orders, we'll dig deeper, since you'll want to generate basic
reports on orders.
But let's start with something simpler: user authentication. Users log in to the
application by providing a username and password. Thus, you'd expect to see the fol-
lowing query pretty frequently:
db.users.findOne({username: 'kbanker',
hashed_password: 'bd1cfa194c3a603e7186780824b04419'})
If the user exists and the password is correct, you'll get back an entire user document;
otherwise, the query will return nothing. This query is acceptable. But if you're con-
cerned with performance, you'll optimize by selecting the _id fields only so that you
can initiate a session. After all, the user document stores addresses, payment methods,
and other personal information. Why send that data across the network and deserial-
ize on the driver side if all you need is a single field? You limit the fields returned
using a projection:
db.users.findOne({username: 'kbanker',
hashed_password: 'bd1cfa194c3a603e7186780824b04419'},
{_id: 1})
The response now consists exclusively of the document's _id field:
{ _id: ObjectId("4c4b1476238d3b4dd5000001") }
There are a few other ways you might want to query the users collection. For instance,
imagine you have an administrative back end allowing you to find users by different cri-
teria. Frequently, you'll want to perform a lookup on a single field, such as last_name :
db.users.find({last_name: 'Banker'})
1
It's important to consider whether these sorts will be efficient. You may choose to rely on your index to handle
sorting for you, but as you add more sort options, the number of indexes grows, and the cost of maintaining
those indexes may not be reasonable. This will be especially true if the number of products per category is
small. We'll discuss this further in chapter 8, but start thinking about these trade-offs now.
Search WWH ::




Custom Search