Database Reference
In-Depth Information
MongoDB isn't so much a matter of mapping out every nook as it is finding the best
ways to accomplish everyday tasks. Through the examples in this chapter, I'll point out
the clearest routes to take. By the end of the chapter, you should have a good intuitive
understanding of queries and aggregation in MongoDB, and you'll be ready to apply
these tools to the design of application schemas.
5.1
E-commerce queries
This section continues our exploration of the e-commerce data model sketched out in
the previous chapter. We've defined a document structure for products, categories,
users, orders, and product reviews. Now, with that structure in mind, we'll look at how
you might query these entities in a typical e-commerce application. Some of these
queries are simple. For instance, _id lookups shouldn't be a mystery at this point. But
we'll also examine a few more sophisticated patterns, including querying for and dis-
playing a category hierarchy, as well as providing filtered views of product listings. In
addition, we'll keep efficiency in mind by looking at possible indexes for some of
these queries.
5.1.1
Products, categories, and reviews
Most e-commerce applications provide at least two basic views of products and catego-
ries. First is the product home page, which highlights a given product, displays
reviews, and gives some sense of the product's categories. Second is the product listing
page, which allows users to browse the category hierarchy and view thumbnails of all
the products within a selected category. Let's begin with the product home page, in
many ways the simpler of the two.
Imagine that your product page URL s are keyed on a product slug. In that case, you
can get all the data you need for your product page with the following three queries:
db.products.findOne({'slug': 'wheel-barrow-9092'})
db.categories.findOne({'_id': product['main_cat_id']})
db.reviews.find({'product_id': product['_id']})
The first query finds the product with the slug wheel-barrow-9092 . Once you have
your product, you query for its category information with a simple _id query on the
categories collection. Finally, you issue another simple lookup that gets all the
reviews associated with the product.
You'll notice that the first two queries use the find_one method but that the last
uses find instead. All of the MongoDB drivers provide these two methods, and so it's
worth recalling the difference between them. As discussed in chapter 3, find returns a
cursor object, whereas findOne returns a document. The findOne just referenced is
equivalent to the following:
db.products.find({'slug': 'wheel-barrow-9092'}).limit(1)
If you're expecting a single document, findOne will return that document if it exists.
If you need to return multiple documents, remember that you'll be using find , and
Search WWH ::




Custom Search