Database Reference
In-Depth Information
that this method will return a cursor. You'll then need to iterate over that cursor some-
where in your application.
Now look again at the product page queries. See anything unsettling? If the query
for reviews seems a bit liberal, you're right. This query says to return all reviews for the
given product, but this wouldn't be prudent in cases where a product had hundreds of
reviews. Most applications paginate reviews, and for this MongoDB provides skip and
limit options. You can use these options to paginate the review document like so:
db.reviews.find({'product_id': product['_id']}).skip(0).limit(12)
You also want to display reviews in a consistent order, which means you have to sort
your query results. If you want to sort by the number of helpful votes received by each
review, you can specify that easily:
db.reviews.find({'product_id': product['id']}).sort(
{helpful_votes: -1}).limit(12)
In short, this query tells MongoDB to return the first 12 reviews sorted by the total
number of helpful votes in descending order. Now, with the skip, limit, and sort in
place, you simply need to decide whether to paginate in the first place. For this, you
can issue a count query. You then use the results of the count in combination with the
page of reviews you want. Your queries for the product page are complete:
product = db.products.findOne({'slug': 'wheel-barrow-9092'})
category = db.categories.findOne({'_id': product['main_cat_id']})
reviews_count = db.reviews.count({'product_id': product['_id']})
reviews = db.reviews.find({'product_id': product['_id']}).
skip((page_number - 1) * 12).
limit(12).
sort({'helpful_votes': -1})
These lookups should use indexes. You've already seen that slugs, because they serve
as alternate primary keys, should have a unique index on them, and you know that all
_id fields will automatically have a unique index for standard collections. But it's also
important that you have an index on any fields acting as references. In this case, that
would include the user_id and product_id fields on the reviews collection.
With the queries for the product home pages in place, you can now turn to the
product listing page. Such a page will display a given category with a browsable listing
of products contained therein. Links to parent and sibling categories will also appear
on the page.
A product listing page is defined by its category; thus, requests for the page will use
the category's slug:
category = db.categories.findOne({'slug': 'outdoors'})
siblings = db.categories.find({'parent_id': category['_id']})
products = db.products.find({'category_id': category['_id']}).
skip((page_number - 1) * 12).
limit(12).
sort({helpful_votes: -1})
Search WWH ::




Custom Search