Database Reference
In-Depth Information
▪ The descendants of a particular category can be easily queried by using a prefix-style reg-
ular expression. For instance, to find all descendants of “bop,” you would use a query like
{_id: /^ragtime:bop:.*/} .
There are a couple of problems with this approach, however:
▪ Displaying the ancestors for a category requires a second query to return the ancestor doc-
uments.
▪ Updating the hierarchy is cumbersome, requiring string manipulation of the _id field.
The solution we've chosen here is to store the ancestors as an embedded array, including the
name of each ancestor for display purposes. We've also switched to using ObjectId() s for
the _id field and moving the human-readable slug to its own field to facilitate changing the
slug if necessary. Our final schema, then, looks like the following:
{ _id : ObjectId (...),
slug : "modal-jazz" ,
name : "Modal Jazz" ,
parent : ObjectId (...),
ancestors : [
{ _id : ObjectId (...),
slug : "bop" ,
name : "Bop" },
{ _id : ObjectId (...),
slug : "ragtime" ,
name : "Ragtime" } ] }
Operations
This section outlines the category hierarchy manipulations that you may need in an ecom-
merce site. All examples in this document use the Python programming language and the py-
mongo driver for MongoDB, but of course you can implement this system using any suppor-
ted programming language.
Read and display a category
The most basic operation is to query a category hierarchy based on a slug. This type of query
is often used in an ecommerce site to generate a list of “breadcrumbs” displaying to the user
just where in the hierarchy they are while browsing. The query, then, is the following:
Search WWH ::




Custom Search