Database Reference
In-Depth Information
Although this approach gives us a nicely normalized model, our queries end up doing a lot of
application-level “joins”:
def
def get_product_with_categories ( product_id ):
product = db . product . find_one ({ "_id" : product_id })
category_ids = [
p_c [ 'category_id' ]
for
for p_c iin db . product_category . find (
{ "product_id" : product_id }) ]
categories = db . category . find ({
"_id" : { "$in" : category_ids } })
return
return product , categories
Retrieving a category with its products is similarly complex. Alternatively, we can store the
objects completely embedded in one another:
// db.product schema
{ "_id" : "My Product" ,
"categories" : [
{ "_id" : "My Category" , ... }
...] }
// db.category schema
{ "_id" : "My Category" ,
"products" : [
{ "_id" : "My Product" , ... }
...] }
Our query is now much simpler:
def
def get_product_with_categories ( product_id ):
return
return db . product . find_one ({ "_id" : product_id })
Ofcourse, if we want to update a product ora category,we must update it in its owncollection
as well as every place where it has been embedded into another document:
def
def save_product ( product ):
db . product . save ( product )
db . category . update (
{ 'products._id' : product [ '_id' ] },
Search WWH ::




Custom Search